问题出在您在粘贴箱中提供的代码中。
您使用了两个 else 语句,因此 Java 会抱怨,因为它不知道在最初的 if 语句之后去哪个。
您需要使用 else if, then else 输入另一个条件语句。例如:
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
etc
}else if (nothing entered) {
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
}
您的代码还有另一个主要问题。您声明变量选项并将其设置在 if 语句中,因此它仅在该 if 语句中具有范围。然后,您退出 if 语句并在我上面提供的代码之前声明一个全新的选项变量。这将不起作用,因为选项整数没有值。
相反,您需要在 if 语句之外声明初始选项 int,如下所示:
int number;
int password = 7123;
int amount = 4000;
int option;
if (number == password) {
etc...
option = userInput.nextInt();
}
此外,您从 if 语句中检查输入的数字与存储的密码以获取提取现金等的输入。这是不好的。就是说if语句对密码校验数字完成后,会自动进入下一段代码。
由于尚未创建扫描仪对象,前三个 if 语句将返回 false,并且您的 else 语句将被打印(无论输入密码是否正确)。
因此,我建议您将该检查放在单独的 else 语句中,并使用 while 循环来确认输入了正确的选择。例如:
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
int option;
number = userInput.nextInt();
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
while (option != 1 || option != 2 || option != 3) {
System.out.println("You didn't enter a valid number. Try again");
option = userInput.nextInt();
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
else if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
else if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}
}
else
System.out.println("The Pin You Entered Was Wrong");
}