空指针异常运行时错误

时间:2014-05-02 08:07:29

标签: java nullpointerexception runtime-error

我已经定义了对象数组的大小。但每当我尝试为客户设置名称时,就会发生错误。 这是我的代码:

    public static void main(String[] args) {

    int customerNum, mainChoice;

    System.out.println("Enter Total Number of Customers Using your System : ");
    Scanner input = new Scanner(System.in);
    customerNum = input.nextInt();
    Customer[] customersArray = new Customer[customerNum];
    mainMenue();
    mainChoice = input.nextInt();

    if (mainChoice == 1) {
        String askLoop = null;

        for (int i = 0; i < customerNum; i++) {
            System.out.println("Enter customer name : ");
            customersArray[i].setName(input.next());
            System.out.println("Enter customer phone number : ");
            customersArray[i].setPhoneNumber(input.next());
            System.out.println("Do you want to Add another Customer (y/n)");
            askLoop = input.next();
            if (askLoop == "y") {
                continue;
            } else {
                break;
            }

        }

    }

class Customer{
private String name;
public void setName(String name){
this.name = name;
    }
}

当我运行它然后输入程序停止的名称并显示此错误:

线程“main”java.lang.NullPointerException中的异常     at ba_1316855_p4.BA_1316855_P4.main(BA_1316855_P4.java:30)

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:2)

使用语句Customer[] customersArray = new Customer[customerNum];,您只创建了一个Customer类的数组。您尚未创建Customer个实例。

您必须稍微修改for循环。

for (int i = 0; i < customerNum; i++) {
        customersArray[i] = new Customer(); // You miss this step.
        System.out.println("Enter customer name : ");

答案 1 :(得分:1)

该行

Customer[] customersArray = new Customer[customerNum];

分配了Customer的引用数组,用null初始化。 您仍然需要使用Customer的实例填充数组,例如在for循环中。

答案 2 :(得分:1)

你不是在访问null初始化数组吗?你的代码导致null.setName(某事物),可能是NullPointerException的来源。

答案 3 :(得分:0)

您已声明您的数组已用任何实例填充它。

for (int i = 0; i < customerNum; i++) {
            Customer c = new Customer ();

            System.out.println("Enter customer name : ");
            c.setName(input.next());
            System.out.println("Enter customer phone number : ");
            c.setPhoneNumber(input.next());
            customersArray[i] = c;
            System.out.println("Do you want to Add another Customer (y/n)");
            askLoop = input.next();
            if (askLoop == "y") {
                continue;
            } else {
                break;
            }

        }