java : NullPointerAccess (NullPointerException) in swith case

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

最佳答案

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

关于java : NullPointerAccess (NullPointerException) in swith case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206076/

相关文章:

java - 缩短switch case方法

java - JTable 在绘制期间抛出 IndexOutOfBoundsException

java - 为什么我的 setOnKeyListener() 不起作用?

java自定义类加载器: some classes are not loaded by my classloader

java - 收到 NullPointerException,不知道为什么

java - 什么是NullPointerException,我该如何解决?

java - 整数和长整型乘法给出不同的答案

java - 如何在 db40 Java 应用程序中调试 "java.lang.NullPointerException"?

php - php 和 codeigniter 中 switch 和 case 的使用

php:根据下拉列表更改变量值