How to re-prompt user input if given incorrect value?

87 Ansichten (letzte 30 Tage)
Niall McKinnon
Niall McKinnon am 24 Sep. 2019
Bearbeitet: Niall McKinnon am 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!

Akzeptierte Antwort

James Tursa
James Tursa am 24 Sep. 2019
Bearbeitet: James Tursa am 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by