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

87 vues (au cours des 30 derniers jours)
Niall McKinnon
Niall McKinnon le 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!

Réponse acceptée

James Tursa
James Tursa le 24 Sep 2019
Modifié(e) : James Tursa le 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by