public class Fraction implements Comparable
{
// a tester method to figure out if Fraction
works...
public static void test() {
Fraction a = new Fraction();
Fraction b = new Fraction();
Fraction c = new Fraction();
a.setValues(5,7);
b.setValues(2,5);
c.setValues(144,12);
c.reduceFraction();
System.out.println(""+c.getNum()+" " + c.getDenominator());
if (a.compareTo(b) > 0)
System.out.println("Greater!");
}
// instance variables to store the numerator and the
denominator
private int num;
private int denominator;
// required by Comparable
public int compareTo(Object ob) {
// as per the instructions, we
can assume that ob is actually a Fraction...
Fraction f = (Fraction) ob;
// convert num and denonimator to
doubles before you divide so you don't round off
double first = ((double)
num) / ((double) denominator);
double second = ((double)
f.getNum())/((double) f.getDenominator());
// return positive if we are
bigger than the parameter
if (first > second)
return 1;
// return negative if we are
smaller than the parameter
if (first < second)
return -1;
// if we aren't bigger, and we
aren't smaller, than we are equal, so return 0
return 0;
}
public void setValues(int numValue, int
denominatorValue) {
num = numValue;
denominator =
denominatorValue;
}
//a method that simply sets
the internal instance variables
public int getNum() {
return num;
}
// a method that returns the
num
public int getDenominator() {
return denominator;
}
// a method that returns the
denominator
public void reduceFraction() {
// the minimum GCF is 1, so
we can use that as a safe value
int biggestfound = 1;
// count a up until it's larger
than denominator or numerator
for (int a = 1; a <=
denominator && a <= num; a++) {
// if a is a
CF of numerator and denominator then we can say the biggest we've found
// as of this
point is in fact a
if
((num % a == 0) && (denominator % a == 0)) biggestfound = a;
}
// divide out denominator and
numerator by the biggest value found
denominator /= biggestfound;
num /= biggestfound;
}
}