2

i keep getting a nullpointer execption whenever i try to call any of my constructor

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


}

4 Answers 4

1

This code:

poly = new Pair[count];

never calls the constructor, and so the next line

poly[count-1].coeff=0;

...fails with an NPE.

All the first line has done is create an array of null references, you haven't created any Pair objects. To actually create the Pair objects, you have to do that:

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;
Sign up to request clarification or add additional context in comments.

Comments

1

It's not enough to just instantiate the array itself. You have to instantiate the elements of your arrays too

public Poly(){

    poly = new Pair[count];
    poly[count-1] = new Pair(/*params*/);
    poly[count-1].coeff=0;
    poly[count-1].exponent=0;
    count++;
}

Comments

0

When you create a new array of objects they default to null so

Pair poly = new Pair[10];
poly[0] == null // true
poly[9] == null // true

You need to initialize your array

public Poly(){

    poly = new Pair[count];
            for(int i=0;i<count;i++) 
                poly[i] = new Pair();
    poly[count-1].coeff=0;
    poly[count-1].exponent=0;
    count++;
}

Comments

0

You create an array-object with the size of count elements.

Every single element within the array is null, so

poly[count-1].coeff=0; 

will thow a NullPointer.

You will have to create Pairs in you Poly sontructor:

for(int i =0;i<count;i++){
    poly[i] = new Pair();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.