多项式添加:无法运行代码

时间:2015-04-27 17:52:21

标签: java arrays throwable default-programs

这个程序在Eclipse上。我必须声明变量"整数"不是" int"。当我编译时,此代码显示没有错误,但存在运行时错误。请解决此问题。

运行时错误:

Exception in thread "main" java.lang.NullPointerException
    at Polynomial.add(Polynomial.java:17)
    at PolynomialTest.main(PolynomialTest.java:7)

Polynomial.java

public class Polynomial{
Integer coef[]; 
Integer exp;     
public Polynomial(Integer a, Integer b) {
    coef = new Integer[b+1];
    coef[b] = a;
    exp = b;
}
// return c = a + b
public Polynomial add(Polynomial b) {
   Polynomial a = this;
   Polynomial c= new Polynomial(0, Math.max(a.exp, b.exp));
   for (Integer i = 0; i <= a.exp; i++){
       c.coef[i] = c.coef[i]  + a.coef[i];
   }
   for (int i = 0; i <= b.exp; i++){
       c.coef[i] += b.coef[i];
   }
   return c;
}
public String toString() {
    if (exp ==  0){
        return "" + coef[0];
    }else
    if (exp ==  1){
        return coef[1] + "x + " + coef[0];
    }
    String s = coef[exp] + "x^" + exp;
    for (int i = exp-1; i >= 0; i--) {
        if      (coef[i] == 0){
            continue;
        }
        else if (coef[i]  > 0){
            s = s + " + " + ( coef[i]);
        }
        if (i == 1){
            s = s + "x";
        }
        else 
            if (i >  1) {
            s = s + "x^" + i;
        }
    }
    return s;
}}

PolynomialTest.java

public class PolynomialTest {
      // test client
    public static void main(String[] args) { 
        Polynomial p1   = new Polynomial(4, 4);
        Polynomial p2   = new Polynomial(7, 2);
        Polynomial p3   = new Polynomial(3, 0);
        Polynomial p    = p1.add(p2).add(p3);   // 4x^3 + 3x^2 + 1
        Polynomial q1   = new Polynomial(2, 2);
        Polynomial q2   = new Polynomial(5, 4);
        Polynomial q    = q1.add(q2);

        System.out.println("p(x) =        " + p);
        System.out.println("q(x) =        " + q);
        System.out.println("p(x) + q(x) = " + p.add(q));
    }
}

1 个答案:

答案 0 :(得分:0)

由于Integer是一个对象,因此您需要使用新的coef对象初始化Integer数组中的每个条目。

您可以在Polynomial构造函数中执行此操作:

public class Polynomial{
Integer coef[]; 
Integer exp;     
public Polynomial(Integer a, Integer b) {
    coef = new Integer[b+1];
    for (int i = 0; i < coef.length; i++){
       coef[i] = new Integer(0);  //create a new Integer and initialize to zero
    }
    coef[b] = a;
    exp = b;
}