首页 > 解决方案 > 在同一循环中将项目添加到多个数组中

问题描述

在赋值中,我们有一个名为的类Product,我们需要为Product对象创建一个数组,并在名为 的类中实现该数组的方法(deletesearchinsertProductArray。我成功编写了数组操作。但是,我有一个关于将Product对象添加到 2 个不同数组中的问题。

public static void main(String[] args) throws IOException { 
    ProductArray array1 = new ProductArray(50);
    ProductArray array2 = new ProductArray(50);
    File file = new File("/Users/S.nur/Downloads/Products.txt");
    Scanner scan = new Scanner(file);
                  
    while (scan.hasNextLine()) {
        String whl = String.valueOf(scan.nextLine());
        String[] split = whl.split(",");
        Product p = new Product(split[0], split[1], Integer.parseInt(split[2]));
               
        array1.insert(p);
        array2.insert(p);   
    }
    array1.display();
    array2.display();
}
    
public class ProductArray {
    private int size;
    private static int count = 0;
    private Product []array;
    private int sortCost=0;
        
    ProductArray(int size){ 
        if (size < 0) {
            throw new IllegalArgumentException("Size cannot be less than 0.");
        }
        this.size = size;
        array = new Product[size]; 
    }
            
    public void insert(Product p){
        if (count >= size) {
            throw new ArrayIndexOutOfBoundsException("Capacity is full.");
        } else {
            array[count++] = p; 
        }
    }
public void display (){
        for (int i= 0; i< count; i++){
            array[i].displayProduct();   
        }
    }
}

但是,我在控制台中遇到了这个异常,我不明白。我该如何解决?

Product name: HUAWEI MATEBOOK D15, Description: AMD RYZEN 7 3700,
Price: 6799 Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "ceng202_lab1.Product.displayProduct()" because
"this.array[i]" is null     at
ceng202_lab1.ProductArray.display(ProductArray.java:141)    at
ceng202_lab1.TestProductArray.main(TestProductArray.java:36)

标签: javaarraysnullpointerexception

解决方案


让我们看一下异常:

Exception in thread "main" java.lang.NullPointerException: 
Cannot invoke "ceng202_lab1.Product.displayProduct()" 
because "this.array[i]" is null at
ceng202_lab1.ProductArray.display(ProductArray.java:141) at 
ceng202_lab1.TestProductArray.main(TestProductArray.java:36)

错误告诉我们在类this.array[i]的方法中是 null 。display()ProductArray

在您的代码中, 的count属性ProductArray是静态的,这意味着它由所有实例共享,而不是每个ProductArray.

这意味着,如果您将一个值插入 的一个实例ProductArray,则count所有实例共享的 都会递增。

如果您随后遍历存储在方法中的一个实例中的所有产品ProductArraydisplay()则数组中将有一些空值:

ProductArray array1 = new ProductArray(50);
ProductArray array2 = new ProductArray(50);

// ProductArray.count is 0
// Both instances of ProductArray have a separate array with 50 values, which are all null

Product p = new Product(split[0], split[1], Integer.parseInt(split[2]));
               
array1.insert(p);
// This inserts a value into array1.array at position 0
// ProductArray.count is incremented to 1


array2.insert(p);   
// This inserts a value into array2.array at position 1
// ProductArray.count is incremented to 2
// array2.array[0] is left empty

for (int i = 0; i < ProductArray.count; i++) {
    array1.array[i].display()
    // will work with i = 0, this is the description that you can see printed in the console.
    // will crash with i = 1, because array1.array[1] is null
}

for (int i = 0; i < ProductArray.count; i++) {
    array2.array[i].display()
    // will crash with i = 0, because array2.array[0] is null
}

要解决此问题,您必须在count 没有关键字的情况下声明static,以便每个实例都有自己的计数。


推荐阅读