这是我的代码:
Scanner in = new Scanner(System.in);
int option;
do{
System.out.println("1. Add Account");
System.out.println("2. Check Balance");
System.out.println("5. Exit");
System.out.print("Enter Choice >> ");
option = in.nextInt();
Account account = null;
switch (option) {
case 1:
try{
System.out.print("Enter id >> ");
int id = in.nextInt();
System.out.print("Enter amount >> ");
double bal = in.nextDouble();
account = new Account(id, bal);
}
catch (InputMismatchException e) {
System.out.println("Invalid input, try again");
}
break;
case 2:
System.out.println(account.getBalance()); // null pointer access here
break;
default:
System.out.println("Invalid option");
break;
}
}
while(option!=5);
在运行过程中,我在检查余额之前添加帐户,从而初始化 account
对象。当我选择选项 2 时,我仍然得到一个 NullPointerException
。我缺少的开关盒有什么特别之处吗?当我在选项 1 之后选择选项 2 时,我的帐户实例发生了什么?
最佳答案
将 Account account = null;
移动到 do 循环之前。
关于java : NullPointerAccess (NullPointerException) in swith case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206076/