Search code examples
javaarraysthrowabledefault-programs

Polynomial Add: Unable to run code


This program is on Eclipse. I have to declare variables "Integer" not "int". When I am compiling this code shows no error but there is a runtime error. Please fix this problem.

Runtime error:

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));
    }
}

Solution

  • Since Integer is an Object, you will need to initialize each entry in your coef array with a new Integer object.

    You could just do this in the Polynomial constructor:

    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;
    }