How do you write a nested if statement that checks if the user has entered certain numbers?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Akana Juliet
il 21 Giu 2021
Commentato: Akana Juliet
il 21 Giu 2021
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!
0 Commenti
Risposta accettata
Scott MacKenzie
il 21 Giu 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!