/**
* Rational implements a rational number as a number
* that can be expressed as the quotient of two integers with
* the following applicable operations: creation, addition,
* and testing for equality.
*
* @author Terence
* @version 1.0
*/
public class Rational {
private int numerator;
private int denominator;
/**
* Constructor to create Rational object
* precondition denominator <> 0
* postcondition
* this.numerator = numerator
* this.denominator = denominator
*
* @param numerator
* @param denominator
* @throw IllegalArgumentException
*/
public Rational(int numerator, int denominator) {
if (denominator != 0) {
this.numerator = numerator;
this.denominator = denominator;
} else throw new IllegalArgumentException("denominator == 0)");
}
/**
* addition method to add two Rationals
* postcondition
* denominator = this.denominator * rhs.denominator
* this.numerator = this.numerator * rhs.denominator +
* this.denominator * rhs.numerator
*
* @param rhs operand Rational
* @return the resulting Rational
*/
public Rational add(Rational rhs) {
return new Rational(numerator * rhs.denominator +
this.denominator * rhs.numerator,
denominator * rhs.denominator);
}
/**
* compare two Rationals
* postcondition
* equal = (this.numerator * rhs.denominator ==
* this.denominator * rhs.numerator)
*
* @param rhs operand Rational
* @return if the two Rational are equal
*/
public boolean equal(Rational rhs) {
return (this.numerator * rhs.denominator ==
this.denominator * rhs.numerator);
}
/**
* reduce the invoking Rational number to its lowest term
*/
public void reduce() {
if (numerator == 0) {
denominator = 1;
}
else {
int gcd = gcd(Math.abs(numerator), denominator);
numerator /= gcd;
denominator /= gcd;
}
}
/**
* toString method to create a string representation of
* the invoking Rational
*
* @return string representing the invoking Rational
*/
public String toString() {
return (numerator + "/" + denominator);
}
/*
* recursive method to find the greatest common divisor of
* two int x and y
*/
private static int gcd(int x, int y) {
if (y == 0)
return x;
else return gcd(y,x%y);
}
}