java:以swith为例的NullPointerAccess(NullPointerException)

are*_*res 2 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 >> ");
        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);
Run Code Online (Sandbox Code Playgroud)

在运行期间,我在检查余额之前添加帐户,因此初始化account对象.当我选择选项2时,我得到了一个NullPointerException.关于开关盒有什么特别之处吗?当我在选项1之后选择选项2时,我的帐户实例会发生什么?

Neb*_*Era 5

Account account = null;在do循环之前移动.