gpt4 book ai didi

java - 调用构造函数时出现空指针异常

转载 作者:行者123 更新时间:2023-11-30 09:15:51 26 4
gpt4 key购买 nike

每当我尝试调用我的任何构造函数时,我都会收到空指针异常

public class Poly{

private static class Pair{

int coeff;
int exponent;

}

int count=1;

private Pair[] poly =new Pair[count];

public Poly(){

poly = new Pair[count];
poly[count-1].coeff=0;
poly[count-1].exponent=0;
count++;
}
public Poly(int coeff1, int exp){

poly = new Pair[count];
//poly.add(new Poly(coeff1, exp));
poly[count-1].coeff=coeff1;
poly[count-1].exponent=exp;
count++;
}

private Poly (int exp) {

poly = new Pair[exp+1];
poly[0].exponent = exp;
}





public String toString(){

String str ="";
for(int i=0; i<=count; i++){
str+= poly[i].coeff +"x^" +poly[i].exponent;
}
return str;
}

public static void main(String[] args) {

Poly p =new Poly(5, 3);
System.out.println(p.toString());
}


}

最佳答案

这段代码:

poly = new Pair[count];

从不调用构造函数,所以下一行

poly[count-1].coeff=0;

...因 NPE 而失败。

第一行所做的只是创建一个null 引用数组,您还没有创建任何Pair 对象。要实际创建 Pair 对象,您必须这样做:

poly = new Pair[count];                    // Not calling the constructor
for (int i = 0; i < poly.length; ++i) {
poly[i] = new Pair(/*...args...*/); // Calling the constructor
}
poly[count-1].coeff=0;

关于java - 调用构造函数时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com