1

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

运行时错误:

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

多项式.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;
}}

多项式测试.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));
    }
}
4

1 回答 1

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;
}
于 2015-04-27T18:30:05.143 回答