我需要用户输入1或2.如果不是1或2,我希望用户再次输入b的值。如果不是1或2,如何提示用户再次输入值?
Matlab代码
b = input('Choose the device Press 1 for the first device Press 2 for the
second device');
switch b
case 1
disp ('Good')
case 2
disp ('Good')
otherwise
Disp('Wrong choice')
% (I want user to enter the value of b again . It must be 1 or 2 . How to prompt user to enter the value again ? )
end
答案 0 :(得分:4)
我会做这样的事情:
success = false;
while ~success
b = input('Choose the device Press 1 for the first device Press 2 for the second device');
switch b
case 1
disp ('Good')
success = true;
case 2
disp ('Good')
success = true;
otherwise
disp('Wrong choice')
success = false;
end
end
通过这种方式,您可以继续循环,直到变量success
变为true
。如果用户输入1或2,它将变为true并且循环退出,否则它将保持为false并再次循环。