필터 지우기
필터 지우기

how to use a while loop for switch case

조회 수: 17 (최근 30일)
Tariq Hammoudeh
Tariq Hammoudeh 2021년 12월 9일
댓글: Jung woo Park 2022년 6월 8일
I have this code:
transactionType= input('1:withdraw 2:deposit 3:account balance 4:end use');
switch transactionType
case 1
.....
case 2
.....
case 3
.....
case 4
.....
otherwise
disp ('invalid')
I need to make it so that, if a number other than 1, 2, 3, or 4 is entered, it displays this message, but also lets me enter a number again.
So is there a way to do that using a while loop.

채택된 답변

Walter Roberson
Walter Roberson 2021년 12월 9일
try_again = true;
while try_again
transactionType= input('1:withdraw 2:deposit 3:account balance 4:end use');
switch transactionType
case 1
if it works out
try_again = false;
end
So when you detect specifically that you are done then set the exit flag.
There is another way:
while true
transactionType= input('1:withdraw 2:deposit 3:account balance 4:end use');
switch transactionType
case 1
if everything works out
break;
end
do not break if you need to try again
Note that you would typically have an indefinite loop anyhow, to allow multiple transactions, continuing until the user ends (or a sanity check is reached)

추가 답변 (1개)

Chunru
Chunru 2021년 12월 9일
repeat = true;
while repeat
transactionType= input('1:withdraw 2:deposit 3:account balance 4:end use');
repeat = false; % this ensures exit if input is valid
switch transactionType
case 1
.....
case 2
.....
case 3
.....
case 4
.....
otherwise
disp ('invalid')
repeat = true; % repeat if invalid
end
end

카테고리

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

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by