필터 지우기
필터 지우기

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

조회 수: 2 (최근 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!

채택된 답변

Scott MacKenzie
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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by