Rational Number Class in Java: Explanation & Practice

Create a Rational class for fractions

Problem summary

Create Rational class that stores numerator/denominator, simplifies, and performs operations.

Starter code

// Create Rational class with:
// - int numerator, denominator
// - simplify(), add(Rational), toString()

public class Main {
    public static void main(String[] args) {
        // Create 1/2 and 1/3, add them
        // Print result as fraction
    }
}

Expected output and test cases

  • 1/2 + 1/3
    5/6
  • 2/4 simplified
    1/2
  • 1/2 + 1/2
    1/1

Hints

  1. Use GCD to simplify
  2. Add: a/b + c/d = (ad+bc)/bd
  3. Then simplify the result

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler