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'.
There should be two operations for the Term:
Input
The first line contains the coefficient and the exponent of the first term. The second line contains the coefficient and the exponent of the second term.
1·1
4·3
Output
Display the resulting product for each of the test case.
4x^4
import java.util.Scanner;
class Term {
private int coefficient;
private int exponent;
public Term() {
}
public Term(int coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
}
/***
* multiplies the term with another term and returns the result
*
*
*/
public Term times(Term t) {
return new Term(t.coefficient * this.coefficient, t.exponent + this.exponent);
}
/**
* prints the coefficient followed by "x^" and appended by the exponent. But
* with the following additional rules:
*
* if the coefficient is 1, then it is not printed.
*
* if the exponent is 1, then it is not printed ( the caret is not printed as
* well)
*
* if the exponent is 0, then only the coefficient is printed.
*/
public String toString() {
if (coefficient == 0) {
return "0";
}
if (coefficient != 1 && exponent == 1) {
return coefficient + "x";
}
if (exponent == 0) {
return coefficient + "";
}
if (coefficient != 1 && exponent != 1 && exponent != 0) {
return coefficient + "x^" + exponent;
}
if (coefficient != 1 && exponent == 0) {
return coefficient + "x";
}
return "x";
}
}
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
String values1[] = keyBoard.nextLine().split(" ");
Term term1 = new Term(Integer.parseInt(values1[0]), Integer.parseInt(values1[1]));
String values2[] = keyBoard.nextLine().split(" ");
Term term2 = new Term(Integer.parseInt(values2[0]), Integer.parseInt(values2[1]));
System.out.println(term1.times(term2).toString());
keyBoard.close();
}
}
Comments
Leave a comment