java:NullPointerAccess(NullPointerException)在swith case中
这是我的代码:java:NullPointerAccess(NullPointerException)在swith case中,java,nullpointerexception,switch-statement,Java,Nullpointerexception,Switch Statement,这是我的代码: 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 >
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);
在运行期间,我将在检查余额之前添加帐户,从而初始化
帐户
对象。当我选择选项2时,仍然会得到一个NullPointerException
。开关箱有什么特别的地方我不知道吗?当我在选项1之后选择选项2时,我的帐户实例发生了什么变化?Moveaccount account=null代码>在do循环之前执行。此操作正常。。但你能解释一下发生了什么吗?在你原来的代码中,当你按2键时,在开关之前,你又为帐户分配了null。