package username.fractions; import java.math.BigInteger; /** * A simple implementation of Fractions. * * @author Samuel A. Rebelsky * @author YOUR NAME HERE * @author CSC152 2005S * @version 1.0 of February 2005 */ public class Fraction { // +------------------+--------------------------------------------- // | Design Decisions | // +------------------+ /* (1) Denominators are always positive. Therefore, negative fractions are represented with a negative numerator. Similarly, if a fraction has a negative numerator, it is negative. (2) Fractions are not necessarily stored in simplified form. To obtain a fraction in simplified form, one must call the simplify method. */ // +--------+------------------------------------------------------- // | Fields | // +--------+ /** The numerator of the fraction. Can be positive, zero or negative. */ BigInteger numerator; /** The denominator of the fraction. Must be non-negative. */ BigInteger denominator; // +--------------+------------------------------------------------- // | Constructors | // +--------------+ public Fraction(BigInteger _num, BigInteger _denom) { this.numerator = _num; this.denominator = _denom; } // Fraction(BigInteger, BigInteger) public Fraction(int _num, int _denom) { // I have two ints. // I need two BigIntegers // How do I go from the ints to BigIntegers? // Hint: Read the documentation for Integer and BigInteger // A really inefficient strategy: // Convert each int to a string // Convert each string to a BigInteger // this.numerator = new BigInteger(Integer.toString(_num)); // this.denominator = new BigInteger(Integer.toString(_denom)); this.numerator = BigInteger.valueOf(_num); this.denominator = BigInteger.valueOf(_denom); } // Fraction(int, int) // +---------+------------------------------------------------------ // | Methods | // +---------+ /** * Express this fraction as a double. */ public double doubleValue() { return this.numerator.doubleValue() / this.denominator.doubleValue(); } // doubleValue() /** * Add the fraction other to this fraction. */ public Fraction add(Fraction addMe) { BigInteger resultNumerator; BigInteger resultDenominator; // The denominator of the result is the // product of this object's denominator // and addMe's denominator resultDenominator = this.denominator.multiply(addMe.denominator); // The numerator is more complicated resultNumerator = (this.numerator.multiply(addMe.denominator)).add(addMe.numerator.multiply(this.denominator)); // Return the computed value return new Fraction(resultNumerator, resultDenominator); } // add(Fraction) /** * Convert this fraction to a string for ease of printing. */ public String toString() { // Lump together the string represention of the numerator, // a slash, and the string representation of the denominator // return this.numerator.toString().concat("/").concat(this.denominator.toString()); return this.numerator + "/" + this.denominator; } // toString() } // class Fraction