public class Ratio { protected int numerator; protected int denominator; public Ratio(int top, int bottom) { numerator = top; denominator = bottom; reduce(); } public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } public double getValue() { return (double)numerator/(double)denominator; } public Ratio add(Ratio other) { return new Ratio(this.numerator*other.denominator+ this.denominator*other.numerator, this.denominator*other.denominator); } protected void reduce() { int divisor = gcd(numerator,denominator); numerator /= divisor; denominator /= divisor; } protected static int gcd(int a, int b) { if (a == 0) { if (b == 0) return 1; else return b; } if (b < a) return gcd(b,a); return gcd(b%a,a); } public String toString() { return getNumerator()+"/"+getDenominator(); } public static void main(String[] args){ Ratio r = new Ratio(1,1); r = new Ratio (1,2); r.add(new Ratio(1,3)); r = r.add(new Ratio(2,8)); System.out.println(r.getValue()); System.out.println(r.toString()); System.out.println(r); } }