Borrar filtros
Borrar filtros

how to use a while loop for switch case

17 visualizaciones (últimos 30 días)
Tariq Hammoudeh
Tariq Hammoudeh el 9 de Dic. de 2021
Comentada: Jung woo Park el 8 de Jun. de 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.

Respuesta aceptada

Walter Roberson
Walter Roberson el 9 de Dic. de 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)

Más respuestas (1)

Chunru
Chunru el 9 de Dic. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by