Null指针异常运行时错误



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

    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中出现异常在ba_1316855_p4.ba_1316855_p4.main(ba_131685._p4.java:30(

我该如何解决这个问题?

使用语句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 : ");

Customer[] customersArray = new Customer[customerNum];

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

您不是在访问初始化为null的数组吗?您的代码导致了null.setName(某种东西(,并且可能是NullPointerException的来源。

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

尝试

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;
            }
        }

最新更新