如何仅循环开关/外壳中的特定"case"?



我使用switch/case根据用户选择的银行账户打印年收入,我想制作这个程序,每当用户输入不正确的输入时,打印"不适当的输入";消息,并允许用户重新输入他们想要选择的银行帐户。但是,目前我的代码只打印";不适当的输入";消息我该怎么修?

public static void main(String[] args) throws Exception
{
//initialize variables
String bank = "";
double money;
//asks the user to type the amount of money
Scanner myinput = new Scanner (System.in);
System.out.print("Please enter the amount of money you want in the bank: ");
//if the input is inappropriate, ensures the user to type the correct input
while (true) {
try {
money = myinput.nextDouble();
break;
} catch (Exception e) {
System.out.println("This is inappropriate. Please enter the amount of money you want in the bank: ");
myinput.nextLine();
} 
}
//asks user to type the type of account they want
System.out.println("Please enter the type of account you want: ");
bank = myinput.next();
//print yearly earnings depending on the type of account that user chose
switch (bank) {
case "A" , "C": //if the user enters A or C, 1.5% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.015 * money)*100)) / 100.0);
break;
case "B": //if the user enters A or C, 2% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.02 * money)*100)) / 100.0);
break;
case "X": //if the user enters A or C, 5% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.05 * money)*100)) / 100.0);
break; 
default:
System.out.println ("This is inappropriate input. Please enter the type of account you want");
bank = myinput.nextLine();
} 
//closing scanner
myinput.close();
}//end main

您可以有一个布尔变量来退出while循环。由于while(false)不会进一步迭代,因此开关/案例中的标志设置为false。

boolean flag = true;
while(flag){
switch(bank){
case "A","C":
System.out.println("You can make $" + (Math.round((0.015 * money)*100)) / 100.0);
flag = false; //put this in all case.
break;
...
}
}
package com.javatutorial;
import java.util.Scanner;
class Main{
public static void main(String[] args) throws Exception
{
String bank = "";
double money = 0;
boolean valid = false;
Scanner myinput = new Scanner (System.in);
System.out.print("Please enter the amount of money you want in the bank: ");
while (true) {
try {
money = myinput.nextDouble();
break;
} catch (Exception e) {
System.out.println("This is inappropriate. Please enter the amount of money you want in the bank: ");
myinput.next();
}
}
do {
System.out.println("Please enter the type of account you want: ");
bank = myinput.next();
switch (bank) {
case "A":
case "C":
System.out.println("You can make $" + (Math.round((0.015 * money) * 100)) / 100.0);
valid = true;
break;
case "B":
System.out.println("You can make $" + (Math.round((0.02 * money) * 100)) / 100.0);
valid = true;
break;
case "X":
System.out.println("You can make $" + (Math.round((0.05 * money) * 100)) / 100.0);
valid = true;
break;
default:
System.out.println("This is inappropriate input. Please enter the type of account you want");
}
}while( !valid);
}
}

最新更新