【发布时间】:2021-10-13 13:08:37
【问题描述】:
目前,我正在从事一个 ATM 项目。我能够让它工作。但是,如果用户在 switch 语句中输入小写字母而不是大写字母,我不确定该怎么办。另外,我是否应该使用 while 循环,以便用户能够重复这些步骤。最后,我坚持如何让用户随时退出程序。例如,完成选择后退出。
public static void main(String[] args) {
double checkingAccount = 5000;
double savingAccount = 2000;
Scanner cin = new Scanner(System.in);
//Welcoming the user!
System.out.println("=======================");
System.out.println("Welcome to SoundBank!");
System.out.println("=======================");
// Selections for the user
System.out.println("Please choose: \nA - Checking Account \nB - Savings Account");
String choice1 = cin.nextLine();
System.out.println("Please choose of the following: \nD - Deposit \nW - Withdrawal \nC - Check Balance \nE - Exit");
String choice2 = cin.nextLine();
// It's time for loops
switch (choice2) {
case "D":
// Checking Account
if (choice1.equalsIgnoreCase("A")) {
System.out.println("How much you do you want to deposit?");
double amount = cin.nextDouble();
double total1 = checkingAccount + amount;
System.out.println("You deposited " + amount);
System.out.println("You currently have: " + total1);
} else
// Saving Account
if (choice1.equalsIgnoreCase("B")) {
System.out.println("How much you do you want to deposit?");
double amount2 = cin.nextDouble();
double total2 = savingAccount + amount2;
System.out.println("You deposited " + amount2);
System.out.println("You currently have: " + total2);
}
break;
case "W":
// Checking Account
if (choice1.equalsIgnoreCase("A")) {
System.out.println("How much do you want to withdraw?");
double amount3 = cin.nextDouble();
double total3 = checkingAccount - amount3;
System.out.println("You withdrew " + amount3);
System.out.println("You currently have: " + total3);
} else
// Saving Account
if (choice1.equalsIgnoreCase("B")) {
System.out.println("How much do you want to withdraw?");
double amount4 = cin.nextDouble();
double total4 = savingAccount - amount4;
System.out.println("You withdrew " + amount4);
System.out.println("You currently have: " + total4);
}
break;
case "C":
// Checking Account
if (choice1.equalsIgnoreCase("A")) {
System.out.println("Your current balance is: " + checkingAccount);
} else
// Saving Account
if (choice1.equalsIgnoreCase("B")) {
System.out.println("Your current balance is: " + savingAccount);
}
break;
case "E":
System.out.println("You exited the program.");
break;
default:
System.out.println("Please choose a selction.");
}
}
【问题讨论】:
-
处理不同大小写的一种简单方法是将所有内容都转换为大写
choice = choice.toUpperCase();(它是“小写”而不是“小写”)
标签: java while-loop switch-statement