Dealing with wrong input
23 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
How do I avoid this error? I would like for users, if they enter a string instead of number to told "Those are not the instructions, please try again"
4 commentaires
Réponses (2)
Stephen23
le 3 Sep 2019
Modifié(e) : Stephen23
le 3 Sep 2019
str = '';
num = NaN;
while isnan(num)
num = str2double(input([str,'Enter a number: '],'s'));
str = 'Please try again! ';
end
And tested:
Enter a number: hello
Please try again! Enter a number: world
Please try again! Enter a number: 42
0 commentaires
Nicolas B.
le 3 Sep 2019
Modifié(e) : Nicolas B.
le 3 Sep 2019
Okay, then I would use the exception catching method:
str = '';
num = NaN;
while isnan(num)
try
num = input('Please enter your guess: ');
catch
disp('You must give a valid number!');
num = NaN;
end
end
1 commentaire
Rik
le 3 Sep 2019
That's also possible, although I think it would make slightly more sense to use Stephen's method, because then it also isn't possible to provide a variable name.
If you define a=9; before your loop, you can enter a in the prompt and it will pass the test. With Stephen's code, that is not possible.
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices 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!