每当我尝试调用任何构造函数时,我都会收到空指针异常
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/