What Causes NullpointerException?

Asked 2 months ago, Updated 2 months ago, 4 views

Two programs have been created to display the contents of the cart.
Cart.java
Item.java
However, if you run it, it becomes NullpointerException.I would like you to tell me how to improve it.
I'm not confident about the array substitution.
Cart.java

public class Cart{
    Items [ ] items;
    int num = 0, i;
    void addItem(Itemx){
        items [num] = x;
        num++;  
    }
    void info() {
        for(i=0;i<=num;i++){
            items [num].toString();
        }
    }

    public static void main(String[]args) {
        System.out.println(Item.getNumberOfInstances());
        Cart cart = new Cart();
        Item i1 = new Item ("PC", 98000);
        Item i2 = new Item ("Display", 40000);
        cart.addItem(i1);
        cart.addItem(i2);
        cart.info();
        System.out.println(Item.getNumberOfInstances());
    }
}

Item.java

public class Item{
    String name;
    int price, i = 0;
    Item(String a, intb){
        this.name=a;
        This.price=b;
        i++;
    }
    intgetNumberOfInstances(){
        returni;
    }
    public String to String (Itemc) {
        return c.name +", "+c.price;
    }
}

java

2022-09-30 11:41

1 Answers

(What has already been pointed out in the comment is that it was a mistake when posting.)

NullpointerException occurs because you have not assigned an array.

The normal array is
Name of data type [ ] array = new data type [array size];
Use as shown in .

For the posted sample, there is no right side, so null initializes and tries to use it, so an exception occurs.

So,
Item[] items=newItem[100];
or

in the constructor items=new int[100];
I'll do it like this.

Also,
Because arrays cannot be scaled, you must be aware of their range when using them.
For example, if you set the size at 100, as in the previous example, num becomes 100, you cannot add any more.

Also,

for(i=0;i<=num;i++){
    items [num].toString();
}

is

for(i=0;i<num;i++){
    items[i].toString();
}

is incorrect (because num is the next substitution position).


2022-09-30 11:41

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.