フィルターのクリア

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 件のコメント
Jung woo Park
Jung woo Park 2022 年 6 月 8 日
thank U so much ❤

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeLoops 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