how to use a while loop for switch case

17 次查看(过去 30 天)
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