-2

I am new to Java and have just beginning doing some exercises a friend sent me. The exercise in question asks us to create a class Term for the terms of a polynomial, and another the class Polynomial itself, where the polynomial is represented as a fixed size array and the values of its fields are provided. I have written the following code:

class Term
{
    int coeff;
    int exponent;
}

public class Polynomial {

    static int size=5;  
    Term[] poly;

    public Polynomial()
    {
        poly = new Term[size];

        for(int i=0;i<size;i++)
        {
            poly[i].coeff=0;
            poly[i].exponent=0;
        }
    }

    public static void main(String args[]) throws Exception
    {
        Polynomial p = new Polynomial();
    }
}

And I keep getting the following exception:

Exception in thread "main" java.lang.NullPointerException
at prac.polynomial.<init>(polynomial.java:25)
at prac.polynomial.main(polynomial.java:34)

Please help me with what I am doing wrong here.

nerdherd
  • 2,508
  • 2
  • 24
  • 40
em.bee
  • 1
  • 2

2 Answers2

2

Array elements for an Object array are nullby default. Make sure they are initialized before attempting to access their fields

for (int i = 0; i < size; i++) {
    poly[i] = new Term();
    ...
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

You created the array of Terms, but it's initialized to all nulls. You need to create your Terms.

for(int i=0;i<size;i++)
{
    poly[i] = new Term();
    poly[i].coeff=0;
    poly[i].exponent=0;
}
rgettman
  • 176,041
  • 30
  • 275
  • 357