MATLAB Answers

User input has to be a natural number between 1 to 15

4 views (last 30 days)
Arko Tuisk
Arko Tuisk on 5 Dec 2019
Commented: Adam Danz on 5 Dec 2019
User has to pick a number between 1 to 15 and that choice will determine which file to load.
I can limit the range to 1 and 15 but if user inserts for example 4.5, pi etc then it does not produce an error.
Is it possible to get the function to display an error and will insist user to pick a new number.
I did use mustBeInteger and it worked fine but it just said error and no further input was required.
Thanks for all the help!
file = input('Pick a number:');
while season > 15 || season < 1
disp('Error!');
file = input('Pick a number:');
end
if file ==1
etc
then it proceeds to load a file depending the input. I can do that part quite well.

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 5 Dec 2019
Edited: Adam Danz on 5 Dec 2019
Simply add the mod() part to your while requirement. mod(x,1)==0 checks that x is an integer.
I also clarified the instrutions in input() so the user knows why s/he is getting an error. And I replaced your disp() with fprintf() to explain why there was an error and to print it in red.
Lastly, it's not clear where the variable season comes from but I trust that you've worked that out and this problem is merely within your demo and not in your actual code.
while season > 15 || season < 1 || mod(season,1)~=0
fprintf(2,'Error: Input must be an integer between 1:15 (inclusive)\n');
season = input('Pick an integer between 1 and 15: ');
end

More Answers (1)

Dale Shpak
Dale Shpak on 5 Dec 2019
% Since MATLAB doesn't have a do-while, the 'while true' prevents
% us from having to have the input command twice in our code
while true
file = input('Pick a number: ');
if fix(file) == file && file >= 1 && file <= 15
break;
end
disp('Number must be an integer between 1 and 15');
end

  0 Comments

Sign in to comment.

Sign in to answer this question.