How to exit an if else loop without continuing with the other lines of code?

조회 수: 4 (최근 30일)
Manuel S Mathew
Manuel S Mathew 2020년 5월 27일
답변: Arjun 2024년 12월 6일
This is my code
prompt = 'Which Schedule Should Be Used? (1/2) \n';
x = input(prompt);
if x == 1
connection = connection_schedule1();
elseif x == 2
connection = connection_schedule2();
else
fprintf('Unrecognized Input \n')
end
connection_schedule1 and connection_schedule2 are two functions that make a schedule for my code. If someone enters any other term than 1 or 2, I would like to display the message 'Unrecognized Input' and exit without proceeding through the next lines of code. Is this possible? Currently, my error message is displayed but it shows also other error in the succeeding lines of code that requires the schedules that I input. It would also be helpful if I can bring back the execution to the first line shown here if an invalid input is provided. Many thanks in advance.
  댓글 수: 1
Stephen23
Stephen23 2020년 5월 27일
"It would also be helpful if I can bring back the execution to the first line shown here if an invalid input is provided"
Use a while or a for loop.

댓글을 달려면 로그인하십시오.

답변 (1개)

Arjun
Arjun 2024년 12월 6일
I see that you want execute different functions based on the user input and if the input is unrecognized then you want them to re-enter their choice.
The current workflow uses an "if-elseif-else" construct, which inherently does not require an explicit exit because only one of the conditions is executed based on its order. If the "if" condition is true, the statements within it are executed, and all subsequent "elseif" and "else" blocks are skipped. If the "if" condition is false, the control checks the "elseif" conditions in sequence. The first true "elseif" condition executes its block, skipping the rest. If none of the "if" or "elseif" conditions are true, the "else" block is executed.
However, this construct does not allow returning to a previous point, which is why a "while" loop is necessary to repeatedly prompt the user until a valid choice is made. In such cases, an infinite "while" loop is used with a "break" statement to exit the loop once a valid input is received.
Kindly refer to the code below for better understanding:
while true
prompt = 'Which Schedule Should Be Used? (1/2) \n';
x = input(prompt);
if x == 1
connection = connection_schedule1();
break; % Exit the loop on valid input
elseif x == 2
connection = connection_schedule2();
break; % Exit the loop on valid input
else
fprintf('Unrecognized Input \n');
% Optionally, you can add a pause or clear command here
% pause(1); % Pause for 1 second before re-prompting
end
end
Kindly refer to the documentation of "while" and "break" for using them efficiently:
I hope this helps!

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by