为什么我收到错误!?(空指针异常)

时间:2014-01-30 01:35:36

标签: java runtime-error

我正在尝试创建一个程序,汽车经销商可以选择什么样的客户,然后输入信息。它可以正常打印结果。然后它给了我底部的错误。请帮忙!! **我还需要一种方法来添加服务对象并打印它们。任何帮助表示赞赏!提前谢谢

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        final int MAX = 9999;
        Customer [] cust = new Customer[MAX];
        int choice = 0;
        int cnt;

        double total;

        for(cnt=0; cnt < MAX && choice == 1 || choice ==2 || choice == 0; cnt++){
            System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press 9");
            choice = s.nextInt();
            switch (choice){
            case 1:
                cust [cnt] = new Service();
                break;
            case 2:
                cust [cnt] = new Purchaser();
                            break;
            default:
                break;
            }
        }
        for(int i=0; i < cnt; i++){
            cust[i].showData();
        }
        //for(int i=0; i < cnt; i++ ){
            //total = cust.
        //}
            s.close();

    }
}
interface Functions {
    public void getData();
    public void showData();
}
abstract class Customer implements Functions {
    protected String name;


}
class Purchaser extends Customer {
    protected double payment;

    public Purchaser(){
        getData();
    }

    public void getData() {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the name of the customer");
        name = s.nextLine();
        System.out.println("Enter payment amount: ");
        payment = s.nextDouble();
    }
    public void showData() {    
        System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);

    }   
}
class Service extends Customer {
    protected String date;
    protected double amount;
    public Service () {
        getData();

    }

    public void getData() {     
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the name of the customer");
        name = s.nextLine();
        System.out.println("Enter date of Service: ");
        date = s.nextLine();
        System.out.println("Enter the cost of Service: ");
        amount = s.nextDouble();
    }
    public void showData() {
        System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
    }
}

Customer name: ;khhihl The date is: ljhljh, the Amount owed is: 555.00
Customer name: ljhjlhhj Payment amount is: 545454.00
Exception in thread "main" java.lang.NullPointerException
    at prog24178.assignment.Assignment3.main(Assignment3.java:30)

1 个答案:

答案 0 :(得分:0)

我建议,在调用showData()的for循环中添加以下语句:

if(cust[i]!=null)

这将确保它永远不会尝试从没有客户的阵列中的空间读取数据。 (空指针异常是由程序试图访问没有数据的对象引起的。)

您可以使用ArrayList<Customer>代替Customer[]解决大部分问题。这样,您可以拥有任意数量的客户,如果您到达已添加的客户的末尾,则不会尝试查找没有客户的地方。