这是我的代码:
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循环之前。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句