我正在创建一个跟踪用户银行账户活动的基本银行应用程序,我似乎不明白为什么当我运行代码时,它只是在运行我为"默认";案例因此,即使当我按下1、2、3或4时,控制台也会显示"1";错误--请选择一个有效的选项">
提前感谢!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
您的程序没有按预期工作的原因是:
- 您正在提示用户输入
- 将该输入捕获为数值;具体地说,基元数据类型
int
- 将
int
输入与各种字符值进行比较,即原始数据类型ch
(如'1'
(的值
下面是你正在做的事情的配对版本:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
这是同一个块,但我将其改为case 1
(与整数值匹配(,而不是case '1'
(与单个字符值匹配(:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
因此,要修复程序,请将各种case
语句更改为使用整数值,而不是字符。