Search code examples
javaarraysnullpointerexception

Adding items into multiple arrrays in the same loop


In assignment, we have a class called Product and we need to need to create a an array for Product objects, and implement this array's methods (delete, search, insert) in a class called ProductArray. I wrote array operations successfully. However, I have a problem about adding Product objects into 2 different arrays.

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

However, I got this exception in the console and I did not understand it. How can I fix it?

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)

Solution

  • Let's have a look at the exception:

    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)
    

    The error tells us that this.array[i] is null in the method display() of the class ProductArray.

    In your code, the count property of ProductArray is static, meaning that it is shared by all instances, instead of being a different value for every instance of ProductArray.

    This means, that if you insert a value into one instance of ProductArray, the count, that all instances share, is incremented.

    If you then iterate over all products stored in one instance of ProductArray in your display() method, there will be some null values in your array:

    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
    }
    
    

    To fix this issue, you have to declare count without the static keyword, so that each instance has its own count.