how to correctly prompt user to enter only 1 real number,numeric value,that is within range...?
12 次查看(过去 30 天)
显示 更早的评论
Says i have to prompt user to enter a value of between 5-10, how do i make sure only 1 value is entered in the command window... and also, how should i make sure it is a real number ( 2i/3j etc is not allowed) This is part of my code..
% Included the 's' because sometimes user tend to enter alphabets or string
A=input('please enter a value from 5-10: ','s');
%loop if more than 1 value is entered
while length(str2num(R))~=1
while (isempty(A) || (str2num(A)<=4 || str2num(A)>=11))
A=input('please enter only 1 number and make sure its in range: ','s');
end
end
When i run the script and enter 1 3 a, this is what happened..
(Please enter the desirable radius value for your tank: 1 3 a
Operands to the and && operators must be convertible to logical scalar values. )
I dont even know if my approach is right... i tried to split loop and its working fine for part 1 but when it comes to range, its not OK.. i need a correct one that works perfectly fine...and also, i dont want any input with i or j.. please help!
0 个评论
采纳的回答
David Sanchez
2014-6-5
A=input('please enter only 1 number and make sure its in range: ','s');
while (isnan(str2double(A)) || str2double(A)<=4 || str2double(A)>=11)
A=input('please enter only 1 number and make sure its in range: ','s');
end
0 个评论
更多回答(2 个)
Julia
2014-6-5
I use this:
x = inputdlg('Please enter an integer between 1 and 4:');
data = str2double(x);
if 1<= data & 4>=data
% do what is desired
else
errordlg('Wrong Input')
end
I don't know, if it detects j and i, but if not, you could use strcmp(). Perhaps your code works, if you just replace "||" with "|". I had some issues with that, too.
Gaurav Shukla
2014-6-5
Given a combination of number and char, num2str will give you empty matrix [], thus u cant compare tha to your range.
i suggest to use isnumeric function to validate the input is numeric.
A=input('please enter a value from 5-10: ','s');
if (isnumeric(A))
while (isempty(A) || (str2num(A)<=4 || str2num(A)>=11))
A=input('please enter only 1 number and make sure its in range: ','s');
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!