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

9 vues (au cours des 30 derniers jours)
Arko Tuisk
Arko Tuisk le 5 Déc 2019
Commenté : Adam Danz le 5 Déc 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.

Réponse acceptée

Adam Danz
Adam Danz le 5 Déc 2019
Modifié(e) : Adam Danz le 5 Déc 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
  2 commentaires
Arko Tuisk
Arko Tuisk le 5 Déc 2019
thank you so much! It worked just fine
Adam Danz
Adam Danz le 5 Déc 2019
Glad I could help!

Connectez-vous pour commenter.

Plus de réponses (1)

Dale Shpak
Dale Shpak le 5 Déc 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

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by