- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathADTFraction.java
80 lines (73 loc) · 2.57 KB
/
ADTFraction.java
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
packagecom.thealgorithms.maths;
publicrecordADTFraction(intnumerator, intdenominator) {
/**
* Initializes a newly created {@code ADTFraction} object so that it represents
* a fraction with the {@code numerator} and {@code denominator} provided as arguments.
*
* @param numerator The fraction numerator
* @param denominator The fraction denominator
*/
publicADTFraction {
if (denominator == 0) {
thrownewIllegalArgumentException("Denominator cannot be 0");
}
}
/**
* Add two fractions.
*
* @param fraction the {@code ADTFraction} to add
* @return A new {@code ADTFraction} containing the result of the operation
*/
publicADTFractionplus(ADTFractionfraction) {
varnumerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator;
vardenominator = this.denominator * fraction.denominator;
returnnewADTFraction(numerator, denominator);
}
/**
* Multiply fraction by a number.
*
* @param number the number to multiply
* @return A new {@code ADTFraction} containing the result of the operation
*/
publicADTFractiontimes(intnumber) {
returntimes(newADTFraction(number, 1));
}
/**
* Multiply two fractions.
*
* @param fraction the {@code ADTFraction} to multiply
* @return A new {@code ADTFraction} containing the result of the operation
*/
publicADTFractiontimes(ADTFractionfraction) {
varnumerator = this.numerator * fraction.numerator;
vardenominator = this.denominator * fraction.denominator;
returnnewADTFraction(numerator, denominator);
}
/**
* Generates the reciprocal of the fraction.
*
* @return A new {@code ADTFraction} with the {@code numerator} and {@code denominator} switched
*/
publicADTFractionreciprocal() {
returnnewADTFraction(this.denominator, this.numerator);
}
/**
* Calculates the result of the fraction.
*
* @return The numerical result of the division between {@code numerator} and {@code
* denominator}
*/
publicfloatvalue() {
return (float) this.numerator / this.denominator;
}
/**
* Returns a string representation of this {@code ADTFraction} in the format
* {@code numerator}/{@code denominator}.
*
* @return A string representation of this {@code ADTFraction}
*/
@Override
publicStringtoString() {
returnString.format("%d/%d", this.numerator, this.denominator);
}
}