java:switch case中的空指针访问(NullPointerException)

时间:2014-10-05 18:54:47

标签: 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);

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

1 个答案:

答案 0 :(得分:5)

Account account = null;移至do循环之前。