| CIT 594 Assignment
1: Fractions Spring 2008, David Matuszek |
I am providing you with a "fractions" class. Copy this class into NetBeans 6.0, add javadoc comments to it (including comments for private elements), and write a complete set of JUnit 4 tests for it (including for the constructor).
The class is complete, except that it does not throw exceptions when it should (hint: division by zero is illegal). Fix this (and test the fix).
package fraction; public class Fraction { private int numerator; private int denominator; public Fraction(int numerator, int denominator) { this.numerator = numerator; this.denominator = denominator; normalizeSigns(); reduceToLowestTerms(); } public Fraction add(Fraction that) { return new Fraction(this.numerator * that.denominator + that.numerator * this.denominator, this.denominator * that.denominator); } public Fraction subtract(Fraction that) { return new Fraction(this.numerator * that.denominator - that.numerator * this.denominator, this.denominator * that.denominator); } public Fraction multiply(Fraction that) { return new Fraction(this.numerator * that.numerator, this.denominator * that.denominator); } public Fraction divide(Fraction that) { return new Fraction(this.numerator * that.denominator, this.denominator * that.numerator); } @Override public boolean equals(Object obj) { Fraction that = (Fraction) obj; return this.numerator * that.denominator == this.denominator * that.numerator; } @Override public String toString() { return numerator + "/" + denominator; } private void normalizeSigns() { if (denominator < 0) { numerator = -numerator; denominator = -denominator; } } private void reduceToLowestTerms() { int gcd = greatestCommonDivisor(numerator, denominator); if (gcd > 1) { numerator /= gcd; denominator /= gcd; } } static int greatestCommonDivisor(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } }
Zip the complete project and submit via Blackboard before midnight Wednesday, January 23.