I have an ArrayList terms with various polynomial terms inside. This is what is inside:
So there are 4 elements inside the array. Each one has their own coefficient and exponent.Values of this: 8.00x^2+1.00+4.00x^2+2.00
I want to do a loop that adds the terms with like exponents and store them in another List P3. I want P3 to have this:
I have tried a for loop that compares the first element of the array with the second, third... and so on. If the exponents match, then I add the coefficients and add a new term with the new coefficient and the exponent to P3.Values of P3: 12.00x^2+3.00
I also put another condition that if the term does not match any other term, then simply add that term into P3.
However, the output I get adds each term over and over. This is the result I get:
This is the full code of the loop I have done so far. Could anyone tell me what I'm doing wrong?Values of P3: 8.00x^2+12.00x^2+8.00x^2+3.00+4.00x^2
for(int i = 0; i <= this.terms.size() - 1; i++) { for(int j = i + 1; j <= this.terms.size() - 1; j++) { if(this.terms.get(i).getExponent() == this.terms.get(j).getExponent()) { double newCoeff = this.terms.get(i).getCoefficient() + this.terms.get(j).getCoefficient(); P3.addTerm(new TermImp(newCoeff, this.terms.get(i).getExponent())); } else if(this.terms.get(i).getExponent() > this.terms.get(j).getExponent()) { double newCoeff = this.terms.get(i).getCoefficient(); int newExp = this.terms.get(i).getExponent(); P3.addTerm(new TermImp(newCoeff,newExp)); } } }
--- Update ---
Now I see that it is comparing each and everyone if the terms and doing an action depending on the comparison. For example, at the start it compares 8x^2 with 1x^0 and doing this line of code:
else if(this.terms.get(i).getExponent() > this.terms.get(j).getExponent()) { double newCoeff = this.terms.get(i).getCoefficient(); int newExp = this.terms.get(i).getExponent(); P3.addTerm(new TermImp(newCoeff,newExp)); }
How can I make it so that only the ones that have like terms add and the other ones are added only once?