package rational; public class RationalNumber implements Comparable { private int numerator; private int denominator; public RationalNumber(int numer, int denom) { numerator = numer; denominator = denom; if (denominator == 0) // handle 0 denominator denominator = 1; if (denominator < 0) { // Make the numerator "store" the sign numerator = numerator * -1; denominator = denominator * -1; } reduce(); } public int compareTo(Object obj) { RationalNumber otherObj = (RationalNumber)obj; double result = getDecimalEquivalent() - otherObj.getDecimalEquivalent(); if (result > 0) return 1; else if (result < 0) return -1; return 0; } public double getDecimalEquivalent( ) { return (double)numerator/denominator; } public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } public RationalNumber reciprocal() { return new RationalNumber(denominator, numerator); } public RationalNumber add(RationalNumber op2) { int newDenom = denominator * op2.getDenominator(); int newNumer = numerator*op2.getDenominator() + op2.getNumerator()*denominator; return new RationalNumber(newNumer, newDenom); } public RationalNumber subtract(RationalNumber op2) { int newDenom = denominator * op2.getDenominator(); int newNumer = numerator * op2.getDenominator() - op2.getNumerator() * denominator; return new RationalNumber(newNumer, newDenom); } public RationalNumber multiply(RationalNumber op2) { int newDenom = denominator*op2.getDenominator(); int newNumer = numerator*op2.getNumerator(); return new RationalNumber(newNumer, newDenom); } public RationalNumber divide(RationalNumber op2) { int newDenom = denominator * op2.getNumerator(); int newNumer = numerator * op2.getDenominator(); return new RationalNumber(newNumer, newDenom); } public boolean equals(RationalNumber op2) { if (numerator == op2.getNumerator() && denominator == op2.getDenominator()) return true; return false; } public String toString() { if (numerator == 0) return "0"; else if (denominator == 1) return numerator + ""; else return numerator + "/" + denominator; } // This assumes that the numerator is not negative private void reduce() { // divide numerator and denominator by gcd to reduce if (numerator != 0) { int common = gcd(Math.abs(numerator), denominator); numerator = numerator / common; denominator = denominator / common; } else denominator = 1; // so 0 is unique } private int gcd(int num1, int num2) { // a slow, non-traditional method while (num1 != num2) if (num1 > num2) num1 = num1 - num2; else num2 = num2 - num1; return num1; } }