how to correctly prompt user to enter only 1 real number,numeric value,that is within range...?
6 ビュー (過去 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 で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!