Next: None. Up: Fraction class example. Previous: Coding.
This gives us the following complete class definition.
import csbsju.cs160.*;
public class Fraction {
public static final Fraction ZERO = new Fraction(0, 1);
public static final Fraction ONE = new Fraction(1, 1);
private int num;
private int den;
public Fraction(int numerator, int denominator) {
if(denominator < 0) {
numerator *= -1;
denominator *= -1;
}
int div = gcd(numerator, denominator);
num = numerator / div;
den = denominator / div;
}
private static int gcd(int a, int b) {
while(b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
}
public double doubleValue() {
return (num + 0.0) / den;
}
public Fraction add(Fraction other) {
return new Fraction(num * other.den + den * other.num,
den * other.den);
}
public Fraction multiply(Fraction other) {
return new Fraction(num * other.num, den * other.den);
}
public int compareTo(Fraction other) {
// first check if they are equal
if(num == other.num && den == other.den) return 0;
// otherwise see which is less
int first = num * other.den;
int second = other.num * den;
if(first < second) return -1;
else return 1;
}
public String toString() {
if(den == 1) {
return "" + num;
} else {
return num + "/" + den;
}
}
public static Fraction parseFraction(String str) {
int numer; // numerator of new fraction
int denom; // denominator of new fraction
int slash = str.indexOf("/");
if(slash < 0) { // the string contains only an integer
numer = Integer.parseInt(str);
denom = 1;
} else {
numer = Integer.parseInt(str.substring(0, slash));
denom = Integer.parseInt(str.substring(slash + 1));
}
return new Fraction(numer, denom);
}
}
Next: None. Up: Fraction class example. Previous: Summary.