How to restrict user inputs?

43 ビュー (過去 30 日間)
RealA
RealA 2019 年 4 月 24 日
コメント済み: Adam Danz 2019 年 4 月 26 日
Hey everyone, just wondering how I could restrict certain user inputs. I want my program to accept two inputs, in this case being 'i' and 'm' and if the user were to enter a number or a different string, my script would keep looping the input question until the user enters the correct value. (Essentialy I just need help on where I commented)
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
while isempty(y)
disp('Blank is an invalid input you are required to enter a number from the options above!')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
end
while %Need a function that if the user enters a number or string other than i or m, then this loop activates.
disp(' Invalid input,please enter the letter ''i'' for an imperial output or ''m'' for a metric output')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
while isempty(y)
disp('Blank is an invalid input you are required to enter the letter ''i'' for an imperial output or ''m'' for a metric output!')
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
end
end
switch y
case 'i'
fahrenheit = (z*9/5)+32
case 'm'
celsius = (z-32)*5/9
end

回答 (1 件)

Adam Danz
Adam Danz 2019 年 4 月 24 日
編集済み: Adam Danz 2019 年 4 月 26 日
inputOK = false;
while ~inputOK
y = input('Please enter the letter ''i'' for an imperial output or ''m'' for a metric output: ', 's');
if ~isempty(y) && ismember(y, {'m', 'i'})
inputOK = true;
end
end
Another option is to use a question dialog box:
answer = questdlg('Please select output type', mfilename, 'imperial', 'metric', 'quit', 'quit');
  2 件のコメント
Jan
Jan 2019 年 4 月 26 日
A simplification of:
if ~isempty(y) && ismember(y, {'m', 'i'})
inputOK = true;
end
is
inputOK = any(ismember(y, {'m', 'i'});
Adam Danz
Adam Danz 2019 年 4 月 26 日
Smart! Thanks for the improvement.
(add one more closed-parenthesis to avoid error).

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

カテゴリ

Help Center および File ExchangeLanguage Fundamentals についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by