我从代码中收到此错误:


  线程“主”中的异常java.lang.NullPointerException
    在MainClass.main(MainClass.java:20)


任何人都可以识别该错误,我认为这与初始化数组有关吗?

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


}

最佳答案

您忘记创建对象

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

09-11 18:12