Polynomial Class
/**
* Basic Polynomial class using a list for the terms
* The list is one (1) based, the poly has a degree of zero.
*/
public class Polynomial
{
private ListReferenceBased termList = new ListReferenceBased();
public void foo(ListInterface someVar) {
System.out.println("foo");
}
public void changeCoeff(int term, int coeff) {
for (int i = degree() + 1; i < term; i++) {
termList.add(i + 1, new Integer(0) );
}
termList.remove(term);
termList.add(term, new Integer(coeff) );
}
public int getCoeff(int i) {
return ((Integer)termList.get(i + 1)).intValue();
}
public int degree() {
return termList.size() - 1;
}
public String toString() {
StringBuffer result = new StringBuffer();
for (int i = degree(); i >= 0; i--) {
int coeff = getCoeff(i);
if ( coeff != 0 ) {
if (result.length() != 0) {
result.append(" + ");
}
if (i > 0) {
if (coeff == 1) {
result.append("X^" + i);
}
else {
result.append(coeff + "X^" + i);
}
}
else {
result.append(coeff);
}
}
} // for
return result.toString();
}
//========== Test Code ============
public static void main(String [] args) {
//foo(termList);
Polynomial poly = new Polynomial();
poly.changeCoeff(4, 1);
poly.changeCoeff(1, 1);
poly.changeCoeff(3, 7);
System.out.println( poly );
}
}
Output: