How to re-prompt user input if given incorrect value?
85 views (last 30 days)
Show older comments
Niall McKinnon
on 24 Sep 2019
Edited: Niall McKinnon
on 24 Sep 2019
I am trying to create a program where the user inputs two numbers that are used as variables. I want to display an error message and re-prompt user input if they give me a non-numerical inout. Here is the code I have so far:
FLAG = false;
while FLAG == false
input = {'Width of sprinkler field (ft):','Spacing from edge of field (ft):'};
input = inputdlg(input);
input = str2double(input);
yMax = input(1);
spacing = input(2);
if (isnumeric(yMax)==1 && isnumeric(spacing)==1)
FLAG = true;
else
msgbox('ERROR. Input numerical value');
end
end
Any help would be appreciated, thanks!
0 Comments
Accepted Answer
James Tursa
on 24 Sep 2019
Edited: James Tursa
on 24 Sep 2019
str2double will turn your inputs into numeric, so you will pass your isnumeric( ) test even if there are problems. Instead, check for NaN. E.g.
if (isnan(yMax)==0 && isnan(spacing)==0)
Side Notes:
input is the name of a MATLAB built-in function. It would be better if you picked a different name for your variable.
You don't really need that FLAG variable for your logic. A simpler approach:
while true
:
if (isnan(yMax)==0 && isnan(spacing)==0)
break;
end
msgbox('ERROR. Input numerical value');
end
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!