-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfraction.java
More file actions
32 lines (26 loc) · 966 Bytes
/
fraction.java
File metadata and controls
32 lines (26 loc) · 966 Bytes
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
public class fraction {
private int numerator;
private int denominator;
public fraction(int numerator, int denominator) {
if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be zero.");
}
this.numerator = numerator;
this.denominator = denominator;
}
public fraction add(fraction other) {
int newNumerator = this.numerator * other.denominator + other.numerator * this.denominator;
int newDenominator = this.denominator * other.denominator;
return new fraction(newNumerator, newDenominator);
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
public static void main(String[] args) {
fraction fraction1 = new fraction(1, 2);
fraction fraction2 = new fraction(3, 4);
fraction result = fraction1.add(fraction2);
System.out.println("Result: " + result);
}
}