by CodeChum Admin
Construct a class called Term. It is going to represent a term in polynomial expression. It has an integer coefficient and an exponent. In this case, there is only 1 independent variable that is 'x'.
more details here. Important!
https://pastebin.com/wMX2BhFk
public class Term {
private int coefficient;
private int exponent;
public Term(int coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
}
public Term times(Term t) {
return new Term(coefficient * t.coefficient, exponent + t.exponent);
}
@Override
public String toString() {
if (coefficient == 1) {
if (exponent == 0) {
return "1";
} else if (exponent == 1) {
return "x";
} else {
return "x^" + exponent;
}
} else {
if (exponent == 0) {
return Integer.toString(coefficient);
} else if (exponent == 1) {
return coefficient + "x";
} else {
return coefficient + "x^" + exponent;
}
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Term term = new Term(in.nextInt(), in.nextInt());
System.out.println(term.times(new Term(in.nextInt(), in.nextInt())));
}
}
Comments
Leave a comment