【问题标题】:Adding items into multiple arrrays in the same loop在同一个循环中将项目添加到多个数组中
【发布时间】:2021-06-19 10:29:38
【问题描述】:

在赋值中,我们有一个名为Product的类,我们需要为Product对象创建一个数组,并在一个类名为ProductArray。我成功编写了数组操作。但是,我在将 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)

【问题讨论】:

  • 请在ProductArray 中向我们展示您对display() 方法的实现
  • 将异常格式化为代码。第一段的目的是什么?

标签: java arrays nullpointerexception


【解决方案1】:

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

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

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

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

驱动类的变化:

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

【讨论】:

    【解决方案2】:

    我们来看看异常:

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

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

    这意味着,如果您将一个值插入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
    }
    
    

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

    【讨论】:

    • 感谢您的解释!现在,我明白了这个问题。祝你有美好的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2015-09-19
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多