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

6 Ansichten (letzte 30 Tage)
Arko Tuisk
Arko Tuisk am 5 Dez. 2019
Kommentiert: Adam Danz am 5 Dez. 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.

Akzeptierte Antwort

Adam Danz
Adam Danz am 5 Dez. 2019
Bearbeitet: Adam Danz am 5 Dez. 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

Weitere Antworten (1)

Dale Shpak
Dale Shpak am 5 Dez. 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

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by