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

标签 java

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

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/

相关文章:

java - 如何保存 OkHttp Client 对象?

java - Spring Cloud Contracts - 没有为主题设置消费者[...]

java - 日期时间加期间显示不正确的时区

java - 如何在另一个 servlet 中传递值?

java - Spring 5 中 ExceptionHandlerExceptionResolver 始终返回 200 响应代码

java - Jersey RESTful Web 服务 gradle 设置

Java:查找数组中 double 的平均值

java - 使用 jdbc4 连接到数据库引擎的通用代码?

java - 如何使用 MVVM 和 Retrofit 将存储库实现到我的项目中

java - 使用 Spring Boot 的 https url 中的用户名和密码