how to correctly prompt user to enter only 1 real number,numeric value,that is within range...?
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
David Sanchez
on 5 Jun 2014
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 Comments
More Answers (2)
Julia
on 5 Jun 2014
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
on 5 Jun 2014
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 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!