Danrex
Danrex

Reputation: 1655

NullPointerException in Java in an Array List

I am going through an exercise in Java trying to improve my lacklustre programming skills. I have built an array of Items (with each Item holding the name and price of an item). This is done in my GroceryBill class and the array seems to have worked. I then add items to the array but when I try to get the total of the array I get NullPointerException. To shorten it to the relevant parts (and if I am missing anything important I can edit it in).

This is the code in the main class.

public class InheritanceDiscountBill {
    public static void main(String[] args){
    // TODO code application logic here
    GroceryBill checkout1 = new GroceryBill();
    Item orange = new Item("Orange", 0.50);
    Item pie = new Item("Pie" , 2.49);
    checkout1.addItem(orange);
    checkout1.addItem(pie);
    checkout1.getTotal();
    }    
}

Item class

public class Item{
    private String name;
    private double price;

    public Item (String n, double p){
        name = n;
        price = p;
    }

    public String getName(){
        return name;
    }

    public double getPrice(){
        return price;
    }
}

GroceryBill class

public class GroceryBill {
Item[] groceryBill;
int counter;

public GroceryBill(){
    groceryBill = new Item[10];
    counter = 0;
}

public void addItem(Item i){   
    groceryBill[counter] = i;
    counter++;
}

public double getTotal(){
    double totalCost = 0;
    for (Item i : groceryBill){
        totalCost = totalCost + i.getPrice();
        System.out.println(i.getPrice());
    }
    return totalCost;
    }   
}

It keeps coming up with Null pointer exception and points to when I call the checkout1.getTotal() method and then the totalCost = totalCost + i.getPrice();.

Is it because the list isn't full and so it is getting null values as it iterates through the list? If so how do I stop this from happening? I'm very new to this so please take it easy and explain things simply. I have read around on the topic but am still lost as to what I am doing wrong.

Upvotes: 1

Views: 187

Answers (2)

Siavosh
Siavosh

Reputation: 2354

As Radiodef said your array is initialized as a 10-length array but later on you only initialized 2 elements of it, so when you loop through it after 2 loops you are trying to run a function of null object

if you just add a line of code to your current code you will be able to use for-each loop as well and it will work, just check if the item is not null and this way you don't need to know how many element you initialized, but when you are storing counter in GrocerryBill Class why not use it as Radiodef said

  public double getTotal(){
     double totalCost = 0;
     for (Item i : groceryBill){
          if ( i != null ){ 
               totalCost = totalCost + i.getPrice();
               System.out.println(i.getPrice());               
           }
      }
     return totalCost;
     }   

Upvotes: 2

Radiodef
Radiodef

Reputation: 37845

You can't use the for-each loop in getTotal normally because your array has null elements:

//                     vv
groceryBill = new Item[10];

You only add two items to the list so elements 2-9 are all null. So use a regular loop that goes until counter.

for(int i = 0; i < counter; i++) {
    // do stuff with groceryBill[i]
}

Using the for-each loop you'd have to do something like this:

for(Item item : groceryBill) {
    if(item != null) {
        // do stuff with non-null element
    }
}

But that is a little excessive because you are iterating farther than you need to.

Upvotes: 3

Related Questions