How do you write a nested if statement that checks if the user has entered certain numbers?

1 vue (au cours des 30 derniers jours)
Hi all, I am trying to implement a way to check if a user has entered a certain number in an already nested if statement.
I am trying to have the user input a number, and if it falls under "badValues" array, then it either exits or goes back to beginning of program. Is there anyway this is possible? I have included the code here that is failing me.
I will shorten it because the other things are irrelevant, but it looks like:
if (modeSelected == 1)
badValues = [8 43 55];
correctRange = setdiff(0:100,badValues);
isRandom = input('Type 1 for random index or 2 for user selected index:\n');
if (isRandom == 1)
% Random function is here blah blah
elseif (isRandom == 2)
userSelected = input('Input index 0-100 except for 8 43 55:\n');
if (userSelected = badValues)
error('Input Error - input index 0-100 except for 8 43 55 )')
end
% userselected function is here blahblah
else
error('Input Error - enter 1 or 2')
end
Thank you in advance!

Réponse acceptée

Scott MacKenzie
Scott MacKenzie le 21 Juin 2021
This is an example of input validation. Here's one method that achieves what you are after. The prompt is repeated until the user enters a correct value.
while true
userSelected = input('Input index 0-100 except for 8 43 55: ');
if (~ismember(userSelected, badValues))
break; % input is OK, exit loop and proceed
end
end

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by