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

65 visualizaciones (últimos 30 días)
Niall McKinnon
Niall McKinnon el 24 de Sept. de 2019
Editada: Niall McKinnon el 24 de Sept. de 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!

Respuesta aceptada

James Tursa
James Tursa el 24 de Sept. de 2019
Editada: James Tursa el 24 de Sept. de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by