X939: Swapping Fields

A rational number is a number that can be represented as the ratio of two integers. For example, 2/3 is a rational number, and you can think of 7 as a rational number with an implicit 1 in the denominator.

For this question you will be working within the following class:

  public class Rational
  {
      private int numerator;
      private int denominator;

      public Rational(int n, int d)
      {
          this.numerator = n;
          this.denominator = d;
      }
  }

Write an invert() method for this class that swaps the numerator and denominator. However, this method should only perform the swap if the numerator is not initally 0.

For example, inverting 7/3 will change the fields to represent 3/7. However inverting 0/9 should do nothing.

This method will not need to return anything and does not need any parameters.

Hint: in the invert() method, you may need to create another variable inside this method to help you with the swap.

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.