Fraction Class in Java: Explanation & Practice
Create a Fraction class with arithmetic operations
Problem summary
Create a Fraction class that can add two fractions and simplify the result.
Starter code
// Create Fraction class with:
// - int numerator, denominator
// - Fraction add(Fraction other)
// - void simplify() using GCD
// - String toString() as "num/den"
public class Main {
public static void main(String[] args) {
// Test case 1: 1/2 + 1/3
// Print: <result>
}
}Expected output and test cases
- 1/2 + 1/3 = 5/6
5/6
- 1/2 + 1/2 = 1
1/1
- 1/4 + 1/2 = 3/4
3/4
Hints
- Common denominator: a*d + b*c / b*d
- Find GCD to simplify
- Divide both by GCD
Related OOP Basics exercises
- Practice Employee Salary Calculator in Java
- Practice Time Class in Java
- Practice Temperature Converter in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler