【发布时间】: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