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
2019-11-16
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!