# Polynomials Arithmetic

• 03-09-2010, 01:19 PM
thisisIT
Polynomials Arithmetic
import java.util.*;

class Term {
private int coefficient;
private int degree;

public Term(int coefficient, int degree) {
this.coefficient = coefficient;
this.degree = degree;
}

public int getCoefficient() {
return coefficient;
}

public int getDegree() {
return degree;
}
}

public class Polynomial {
private char polyVar;
private ArrayList<Term> terms;

public Polynomial(char polyVar, int ... coefsAndDegs) {
// accept only 'a' through 'z' as the polynomial variable..
if (polyVar < 'a' || polyVar > 'z') {
throw new IllegalArgumentException("Invalid polynomial variable.");
} else {
this.polyVar = polyVar;
}

// check that coefsAndDegs are provided in pairs..
if (coefsAndDegs.length % 2 != 0) {
throw new IllegalArgumentException("Coefficients and Degrees must be provided in pairs.");
} else {
terms = new ArrayList<Term>();

for (int i = 0; i < coefsAndDegs.length / 2; i++) {
Term term = new Term(coefsAndDegs[i * 2], coefsAndDegs[i * 2 + 1]);
}
}
}

-----------------------------------------------------------------------
// **OTHER CLASS** my main method where user will input two polynomial

public static Polynomial enterPolynomial(String entPoly){
Scanner kb = new Scanner(System.in);
System.out.print(entPoly + "\n\tEnter Polynomial Variable(a-z): ");
char variable = kb.nextLine().charAt(0);
System.out.print("\tEnter number of terms of Polynomial: ");
String[] temp = kb.nextLine().split(" ");

int[] coefsDegs = new int[temp.length];
for(int i = 0; i<coefsDegs.length; i++){
coefsDegs[i] = Integer.parseInt(temp[i]);
}
Polynomial poly = new Polynomial(variable, coefsDegs);
return poly;
}

hard lol. i cant make a method on how to add, subtract, and multiply and even evaluate . can someone help me?
• 03-09-2010, 01:44 PM
JosAH
Quote:

Originally Posted by thisisIT
hard lol. i cant make a method on how to add, subtract, and multiply and even evaluate . can someone help me?

Better use a Map<Integer, Integer> where the key is the exponent and the value is the coefficient. That way you can easily find the terms you need.

kind regards,

Jos
• 03-09-2010, 02:07 PM
thisisIT
but, im just new to java.
can give me some example?
do you mind chatting wit me? just in short time. just wanna ask something.
*RUSHING*
• 03-09-2010, 02:27 PM
thisisIT