Dealing with wrong input
12 views (last 30 days)
Show older comments
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"
![Screenshot 2019-09-03 at 12.40.08.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/236807/Screenshot%202019-09-03%20at%2012.40.08.png)
4 Comments
Answers (2)
Nicolas B.
on 3 Sep 2019
Edited: Nicolas B.
on 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 Comment
Rik
on 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.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!