How to request a specific user input?

265 ビュー (過去 30 日間)
Hannah
Hannah 2021 年 8 月 20 日
コメント済み: Awais Saeed 2021 年 8 月 20 日
I want to ask the user if they want to EXP1 or EXP2. If the user enters '1' or '2', then I want to display "running exp 1 or 2", otherwise I want the program to display error message until the user enters '1' or '2'.
prompt = input('Please enter 1 for EXP1 and 2 for EXP2:'); % ask
EXP = input(prompt);
if EXP == 1 || 2 % if the user doesnt input 1 or 2
disp('running exp 1 or 2')
else
EXP = input('ERROR. Please enter 1 for EXP1 and 2 for EXP2:'); %ask again
end
disp(EXP)
This is the code I wrote so far but I don't think that the logic is correct and I also when I try to input '1' or '2' I get the error:
"The first argument to INPUT must be a string or character"
  2 件のコメント
Awais Saeed
Awais Saeed 2021 年 8 月 20 日
Use
EXP = prompt;
It works for me
Hannah
Hannah 2021 年 8 月 20 日
Thanks, now my error is gone. But why if I enter a value that isn't 1 or 2, I dont get a warrning message?

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

採用された回答

Awais Saeed
Awais Saeed 2021 年 8 月 20 日
This is the corrected version of your code
prompt = input('Please enter 1 for EXP1 and 2 for EXP2:');
EXP = prompt; % No need to do input(prompt);
if (EXP == 1 || EXP == 2) % do no write EXP == 1 || 2. Its incorrect
disp('running exp 1 or 2')
else
EXP = input('ERROR. Please enter 1 for EXP1 and 2 for EXP2:');
end
disp(EXP)
Note that after displaying 'ERROR.....', your program just stops and do not process with the newly entered value
  3 件のコメント
Hannah
Hannah 2021 年 8 月 20 日
Perfect! That's what I wanted :) thanks
Awais Saeed
Awais Saeed 2021 年 8 月 20 日
you are welcome.

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

その他の回答 (2 件)

Alan Stevens
Alan Stevens 2021 年 8 月 20 日
You don't need "input" twice:
prompt = 'Please enter 1 for EXP1 and 2 for EXP2:'; % ask
EXP = input(prompt);
if EXP == 1 || 2 % if the user doesnt input 1 or 2
disp('running exp 1 or 2')
else
EXP = input('ERROR. Please enter 1 for EXP1 and 2 for EXP2:'); %ask again
end
disp(EXP)
  1 件のコメント
Hannah
Hannah 2021 年 8 月 20 日
Thanks, I removed the first input and my error is gone. But why if I enter a value that isn't 1 or 2, e.g. 3 I dont get a warrning message?

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


Simon Chan
Simon Chan 2021 年 8 月 20 日
May do this ina while loop
prompt = 'Please enter 1 for EXP1 and 2 for EXP2:'; % ask
EXP = input(prompt);
while (EXP ~= 1 && EXP ~= 2) % if the user doesnt input 1 or 2
EXP = input('ERROR. Please enter 1 for EXP1 and 2 for EXP2:');
end
disp('running exp 1 or 2')
disp(EXP)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by