how to validate the built in input function

3 次查看(过去 30 天)
Hi i have an input function that has a choice for 1 to be true and 0 to be false. im wondering how to validate this function so that if anything other then 0 or 1 is entered the loop will print that it is not a correct value if 0 or 1 are not entered
my code so far is
enter1 = false;
enter = true;
while (enter || ~valid)
enter = false;
choice = input('Would you like to play No Thanks? Enter 1 for yes and 0 for no!==>');
%determine if input is valid
valid = (choice ==1 || choice ==0);
if ~valid
fprintf('The entered number is not 1 or 0.Please enter 1 or 0\n')
end
end
  2 个评论
JESUS DAVID ARIZA ROYETH
what you did is correct, another way could be:
enter=true;
while enter
choice = input('Would you like to play No Thanks? Enter 1 for yes and 0 for no!==>');
enter = not((choice ==1 || choice ==0));
if enter
fprintf('The entered number is not 1 or 0.Please enter 1 or 0\n')
else
break;
end
end

请先登录,再进行评论。

回答(1 个)

Matt Bowring
Matt Bowring 2019-11-16
You could add something like this:
if choice ~= 1 || choice ~= 0:
error('Please enter either a 1 or 0.')
end
If you don't want your script to return an error, but rather 'print' out a statement, you could also do this:
if choice ~= 1 || choice ~= 0:
disp('Please enter either a 1 or 0.')
end

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by