how to use a while loop for switch case

58 Ansichten (letzte 30 Tage)
Tariq Hammoudeh
Tariq Hammoudeh am 9 Dez. 2021
Kommentiert: Jung woo Park am 8 Jun. 2022
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.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 9 Dez. 2021
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)

Weitere Antworten (1)

Chunru
Chunru am 9 Dez. 2021
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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by