How do you write a nested if statement that checks if the user has entered certain numbers?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Akana Juliet
el 21 de Jun. de 2021
Comentada: Akana Juliet
el 21 de Jun. de 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 comentarios
Respuesta aceptada
Scott MacKenzie
el 21 de Jun. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!