how to validate the built in input function

2 views (last 30 days)
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 Comments
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH on 16 Nov 2019
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

Sign in to comment.

Answers (1)

Matt Bowring
Matt Bowring on 16 Nov 2019
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

Categories

Find more on Argument Definitions in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!