blob: 67bcf045b14ed769b670b5b4ae2f24574d555fdb (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
package polynomial;
import java.util.Scanner;
/**
* For representing terms in a polynomial.
*
* @author Sjaak Smetsers
* @version 1.0
* @date 15-02-2012
*/
public class Term {
/**
* Each term consists of a coefficient and an exponent
*/
private double coefficient;
private int exponent;
/**
* a get-method for the exponent
*
* @return exponent
*/
public int getExp() {
return exponent;
}
/**
* a get-method for the coefficient
*
* @return coefficient
*/
public double getCoef() {
return coefficient;
}
/**
* A two-argument constructor
*
* @param c the value for the coefficient
* @param e the value for the exponent
*/
public Term(double c, int e) {
coefficient = c;
exponent = e;
}
/**
* A copy-constructor
*
* @param t the term to be copied
*/
public Term(Term t) {
this(t.coefficient, t.exponent);
}
/**
* For adding two terms with equal exponents
*
* @param t the term added to this
* @require exponent == t.exponent
*/
public void plus(Term t) {
coefficient += t.coefficient;
}
/**
* For multiplying two terms
*
* @param t the multiplier
*/
public void times(Term t) {
exponent += t.exponent;
coefficient *= t.coefficient;
}
/**
* Converts a term into a readable representation the standard format is
* %fx^%d
*
* @return the string representing the term
*/
@Override
public String toString() {
if (exponent == 0) {
return String.format("%f", coefficient, exponent);
} else if (exponent == 1) {
return String.format("%fx", coefficient, exponent);
} else {
return String.format("%fx^%d", coefficient, exponent);
}
}
/**
* Standard implementation of equality
*/
@Override
public boolean equals(Object may_be_term) {
if (may_be_term == null || getClass() != may_be_term.getClass()) {
return false;
} else {
Term term = (Term) may_be_term;
return exponent == term.exponent
&& coefficient == term.coefficient;
}
}
/**
* A static method for converting scanner input into a term. The expected
* format is two numbers (coef, exp) separated by whitespaces. The coef
* should be either an integer or a decimal number. The exp is an integer.
*
* @param s the scanner providing the input
* @return null if no term could be found, the found term otherwise
*/
public static Term scanTerm(Scanner s) {
String coef_patt = "\\-?\\d+(\\.\\d+)?";
if (s.hasNext(coef_patt)) {
String coef = s.next(coef_patt);
int exp = s.nextInt();
return new Term(Double.parseDouble(coef), exp);
} else {
return null;
}
}
}
|