/** * A Class for implementing the data type fraction * Modified with accessor, mutator and helper methods * * @author Mr J * @version 20040217 */ public class NewFraction { private int numerator; // top part private int denominator; // bottom part /** * Constructor for objects of class Fraction */ public NewFraction() { // initialise instance variables setNumerator(0); setDenominator(1); } /** * Construct a fraction given two ints (numerator first) * * @param n the numerator * @param d the denominator * @throws FractionException */ public NewFraction(int n, int d) throws FractionException { if (d != 0) { setNumerator(n); setDenominator(d); } else { throw new FractionException("Denominator can't be zero"); } } /** * A method to add two fractions * * @param a a NewFraction * @param b another NewFraction * @return the sum of fractions a and b */ public static NewFraction add(NewFraction a, NewFraction b) throws FractionException { // find the common denominator, multiply the numerators int cd = (a.denominator * b.denominator); a.numerator = a.numerator * b.denominator; b.numerator = b.numerator * a.denominator; // now add them int nm = a.numerator + b.numerator; // just return a new (simplified) fraction instance NewFraction newOne = new NewFraction(nm, cd); newOne.simplify(); return newOne; } /** * sets the numerator field * * @param n top part of fraction */ public void setNumerator(int n) { this.numerator = n; } /** * sets the denominator field * * @param d bottom part of fraction */ public void setDenominator(int d) { this.denominator = d; } /** * reduces fraction to lowest common denominator */ public void simplify() { int start = numerator; boolean done = false; while ( (!done) && (start > 1) ) { // check that the numerator can be divided exactly by start if (numerator%start == 0) { // see if the denominator can be divided exactly by the same number if (denominator%start == 0) { // got a result numerator = numerator / start; denominator = denominator / start; done = true; } } start = start - 1; } } /** * Override toString() method of Class Object * * @return a String representation of the Fraction */ public String toString() { return("" + numerator + "/" + denominator); } }