So I am making a program that takes in polynomial functions and does different things with it.
Right now, I am trying to make a method that checks the Polynomial that is input, which is stored as an ArrayList
, and condensing it so everything with the same exponent gets added together.
I keep receiving a NullPointer Exception
whenever I run the program, and I am not sure why I am receiving this. I know what the error means, but I have looked through my code and cannot see why the Polynomial is being seen as null
.
This is my constructor
public ArrayList<PolyTerm> terms;
public Poly(ArrayList<PolyTerm> terms)
{
sort(terms);
condenseExponents();
this.terms = terms;
}
And in my main class I have my Poly
objects created like this:
PolyTerm poly1 = new PolyTerm(4, 3);
PolyTerm poly2 = new PolyTerm(-3, 1);
PolyTerm poly3 = new PolyTerm(15, 3);
PolyTerm poly4 = new PolyTerm(7, 2);
PolyTerm poly5 = new PolyTerm(14, 12);
PolyTerm poly6 = new PolyTerm(2, 0);
PolyTerm poly7 = new PolyTerm(19, 2);
ArrayList<PolyTerm> terms = new ArrayList<>();
terms.add(poly1);
terms.add(poly2);
terms.add(poly3);
terms.add(poly4);
ArrayList<PolyTerm> terms1 = new ArrayList<>();
terms1.add(poly5);
terms1.add(poly6);
terms1.add(poly7);
Poly test = new Poly(terms);
Poly test2 = new Poly(terms1);
Where the first thing being taken in by the PolyTerm
is the coefficient, and the second thing being taken in is the exponent.
So back to the Poly class.
In my constructor, I call condenseExponents()
which is meant to condense to ArrayList
and combine the coefficients of all similar exponents. Here is that method
private void condenseExponents()
{
for(int i = 0; i < terms.size() - 1; i++)
{
for(int j = i + 1; j < terms.size(); j++)
{
if(terms.get(i).getExponent() == terms.get(j).getExponent())
terms.set(i, new PolyTerm(terms.get(i).getCoef() + terms.get(j).getCoef(), terms.get(i).getExponent()));
terms.remove(j);
}
}
}
The NullPointer Exception
keeps being thrown on the first line of the for loop
in that method.
Does anybody know why?
Assign term before your function call;
public ArrayList<PolyTerm> terms;
public Poly(ArrayList<PolyTerm> terms)
{
sort(terms);
this.terms = terms;
condenseExponents();
}