how to validate the built in input function

2 vues (au cours des 30 derniers jours)
Ryan Littlejohn
Ryan Littlejohn le 16 Nov 2019
Commenté : Ryan Littlejohn le 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 commentaires
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH le 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
Ryan Littlejohn
Ryan Littlejohn le 16 Nov 2019
thanks!

Connectez-vous pour commenter.

Réponses (1)

Matt Bowring
Matt Bowring le 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

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by