Edited I wrote a method that adds term objects to a polynomial class using array store the term objects, now I want to use ArrayList instead of array. I changed the array to arraylist using get() and add(), but the program is not giving me the correct answer no more. Here's the method after I changed:
public void addTerm(int c, int e) {
for (int i = 0; i < terms.size(); i++) {
// if term with exponent not exist
if (terms.get(i) == null) {
// no coefficients of zero are stored
if (c == 0) {
return;
}
terms.add(new Term(c, e) );
return;
}
// if term with exponent already exist
if (terms.get(i).getExponent() == e) {
int coe = terms.get(i).getCoefficient();
int newCoe = coe + c;
// no coefficients of zero are store
if (newCoe == 0) {
terms.add(null);
return;
}
terms.get(i).setCoefficient(newCoe);
return;
}
}
}
Here's the original code:
public void addTerm(int c, int e) {
for (int i = 0; i < termSize; i++) {
// if term with exponent not exist
if (terms[i] == null) {
// no coefficients of zero are store
if (c == 0) {
return;
}
terms[i] = new Term(c, e);
return;
}
// if term with exponent already exist
if (terms[i].getExponent() == e) {
int coe = terms[i].getCoefficient();
int newCoe = coe + c;
// no coefficients of zero are store
if (newCoe == 0) {
terms[i] = null;
return;
}
terms[i].setCoefficient(newCoe);
return;
}
}
}