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

45 ビュー (過去 30 日間)
Niall McKinnon
Niall McKinnon 2019 年 9 月 24 日
編集済み: Niall McKinnon 2019 年 9 月 24 日
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!

採用された回答

James Tursa
James Tursa 2019 年 9 月 24 日
編集済み: James Tursa 2019 年 9 月 24 日
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
  1 件のコメント
Niall McKinnon
Niall McKinnon 2019 年 9 月 24 日
編集済み: Niall McKinnon 2019 年 9 月 24 日
Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by