Java – Exception in thread “main” java.lang.NullPointerException on Java Array

arraysjavanullpointerexception

I'm getting this error from my code:

Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:20)

Could anyone identify the error, I think it has something to do with initializing my array?

MainClass.java

public class MainClass {


public static void main(String[] args) {

    //dummy vars to simulate user input
    double price = 2.75;

    //declare an array of wincalcs 
    WinCalc[] staging1;
    staging1 = new WinCalc[100];


    for (int x=0; x<staging1.length; x++ ) {
        staging1[x].price = price;
        staging1[x].quantity = x+1;
        staging1[x].calcTotal();    
    }



}

}

WinCalc.java

public class WinCalc {

public double price;
public double quantity;
public double total;

public WinCalc () {
    price= 0;
    quantity = 0;
    total = 0;
}

public void calcTotal() {
    this.total = price * quantity;
}

}

Best Solution

You forgot to create the objects

for (int x=0; x<staging1.length; x++ ) {
    staging1[x] = new WinCalc();   
    // ...
}