MATLAB Answers

how to validate the built in input function

4 views (last 30 days)
Ryan Littlejohn
Ryan Littlejohn on 16 Nov 2019
Commented: Ryan Littlejohn on 16 Nov 2019
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

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags


Translated by