Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java:NullPointerAccess(NullPointerException)在swith case中_Java_Nullpointerexception_Switch Statement - Fatal编程技术网

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时,我的帐户实例发生了什么变化?

Move
account account=null在do循环之前执行。

此操作正常。。但你能解释一下发生了什么吗?在你原来的代码中,当你按2键时,在
开关之前,你又为帐户分配了null。