在同一循环中将项目添加到多个数组中

Adding items into multiple arrrays in the same loop

在赋值中,我们有一个叫做Product的class,我们需要为Product个对象创建一个数组,并实现这个数组的方法(delete, search, insert) 在一个名为 ProductArray 的 class 中。我成功地编写了数组操作。但是,我在将 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)

让我们看一下异常:

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] 在 class ProductArray 的方法 display() 中为 null。

在您的代码中,ProductArraycount 属性 是静态的,这意味着它由所有实例共享,而不是 [= 的每个实例都有不同的值14=].

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

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

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
}

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

线程“main”中的异常java.lang.NullPointerException:无法调用“ceng202_lab1.Product.displayProduct()”,因为“this.array[i]”在

处为空

出现上述错误是因为新创建的产品没有正确插入array1。请检查 ProductArray class 的插入方法,以及您是否在数组中的正确索引处插入新产品。

下面是 ProductArray Class 使用插入方法的一种可能实现:

public class ProductArray {
    Product[] productArray;

    public ProductArray(int size) {
        this.productArray = new Product[size];
    }
    
    /* index variable to insert product at next index, also since you want insert product in 2 different arrays of the ProductArray object,static variable will not be useful */
    public void insert(Product p, int index){
        productArray[index] = p;
    }
}

驱动程序的变化Class:

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

            int index = 0;
            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]));
                Product p2 = new Product(split[0], split[1], Integer.parseInt(split[2]));
                array1.insert(p,index);
                array2.insert(p2,index);
                index++;   
            }
            array1.display();
            array2.display();
    }