How do you write a nested if statement that checks if the user has entered certain numbers?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Scott MacKenzie
2021-6-21
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!