The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | May 2017 |
| Last Sign in: | 398 Weeks Ago, 6 Days Ago |
| Questions Answered: | 66690 |
| Tutorials Posted: | 66688 |
MCS,PHD
Argosy University/ Phoniex University/
Nov-2005 - Oct-2011
Professor
Phoniex University
Oct-2001 - Nov-2016
* This class represents a fraction whose numerator and denominator are integers.
* Requirements:
Implement interfaces: FractionInterface and Comparable (i.e. compareTo())
Implement methods equals() and toString() from class Object
Should work for both positive and negative fractions
Must always reduce fraction to lowest term
For numerators such as 3/-10, it is same as -3/10 (see hints 2. below)
Must display negative fraction as -x/y,
example: (-3)/10 or 3/(-10), must display as -3/10
Must throw FractionException in case of errors, do not throw other types of exception objects
Must not add new or modify existing data fields
Must not add new public methods
May add private methods
* Hints:
* 1. To reduce a fraction such as 4/8 to lowest terms, you need to divide both the numerator and the denominator by their greatest common denominator.
The greatest common denominator of 4 and 8 is 4, so when you divide the numerator and denominator of 4/8 by 4, you get the fraction 1/2.
The recursive algorithm which finds the greatest common denominator of two positive integers is implemnted (see code)
   Â
* 2. It will be easier to determine the correct sign of a fraction if you force the fraction's denominator to be positive. However, your implementation must handle negative denominators that the client might provide.  Â
* 3. You need to downcast reference parameter FractionInterface to Fraction if you want to use it as Fraction. See add, subtract, multiply and divide methods
* 4. Use "this" to access this object if it is needed
************************************************************************************/
package PJ1;
public class Fraction implements FractionInterface, Comparable
{
  private  int numerator; Â
  private  int denominator; Â
  public Fraction()
  {
     // set fraction to default = 0/1
  }  // end default constructor
  public Fraction(int numerator, int denominator)
  {
     // implement this method!
  }  // end constructor
  public double toDouble()
  {
     // return double floating point value
     // implement this method!
     return 0.0;
  }  // end toDouble
  public FractionInterface add(FractionInterface secondFraction)
  {
     // return a new Fraction object
     // a/b + c/d is (ad + cb)/(bd)
     // implement this method!
     return null;
  }  // end add
  public FractionInterface subtract(FractionInterface secondFraction)
  {
     // return a new Fraction object
     // a/b - c/d is (ad - cb)/(bd)
     // implement this method!
     return null;
  }  // end subtract
  public FractionInterface multiply(FractionInterface secondFraction)
  {
     // return a new Fraction object
     // a/b * c/d is (ac)/(bd)
     // implement this method!
     return null;
  }  // end multiply
  public FractionInterface divide(FractionInterface secondFraction)
  {
     // return a new Fraction object
     // return FractionException if secondFraction is 0
     // a/b / c/d is (ad)/(bc)
     // implement this method!
     return null;
  }  // end divide
  public FractionInterface getReciprocal()
  {
     // return a new Fraction object
     // return FractionException if secondFraction is 0
     // implement this method!
     return null;
  } // end getReciprocal
  public boolean equals(Object other)
  {
     // implement this method!
     return false;
  } // end equals
  public int compareTo(Fraction other)
  {
     // implement this method!
     return 0;
  } // end compareTo
 Â
  public String toString()
  {
     return numerator + "/" + denominator;
  } // end toString
  /** Task: Reduces a fraction to lowest terms. */
       //-----------------------------------------------------------------
       // private methods start here
       //-----------------------------------------------------------------
  private void reduceToLowestTerms()
  {
               // implement this method!
               //
               // Outline:
               // compute GCD of numerator & denominator
               // greatestCommonDivisor works for + numeratorbers.
               // So, you should eliminate - sign
               // then reduce numeratorbers : numerator/GCD and denominator/GCD
    Â
     int gcd = greatestCommonDivisor(Math.abs(numerator), Math.abs(denominator));
     numerator = numerator / gcd;
     denominator = denominator / gcd;
  }  // end reduceToLowestTerms
  /** Task: Computes the greatest common secondFraction of two integers.
  * @param integerOne  an integer
  * @param integerTwo  another integer
  * @return the greatest common divisor of the two integers */
  private int greatestCommonDivisor(int integerOne, int integerTwo)
  {
     int result;
     if (integerOne % integerTwo == 0)
        result = integerTwo;
     else
        result = greatestCommonDivisor(integerTwo, integerOne % integerTwo);
     return result;
  }  // end greatestCommonDivisor
  /** Task: Adjusts the signs of the numerator and denominator so that the
  * numerator's sign is the sign of the fraction and the denominator's
   * sign is +. */
  private void adjustSigns()
  {
     if (((numerator > 0) && (denominator < 0)) || ((numerator < 0) && (denominator < 0))) {
        numerator = -numerator;
        denominator = -denominator; Â
     }
  }  // end adjustSigns
  //-----------------------------------------------------------------
  // Simple test is provided here
  public static void main(String[] args)
  {
     FractionInterface firstOperand = null;
     FractionInterface secondOperand = null;
     FractionInterface result = null;
               double doubleResult = 0.0;
     Fraction nineSixteenths = new Fraction(9, 16);  // 9/16
     Fraction oneFourth = new Fraction(1, 4);       // 1/4
     System.out.println("\n=========================================");
     // 7/8 + 9/16
     firstOperand = new Fraction(7, 8);
     result = firstOperand.add(nineSixteenths);
     System.out.println("The sum of " + firstOperand + " and " +
           nineSixteenths + " is \t\t" + result);
     // 9/16 - 7/8
     firstOperand = nineSixteenths;
     secondOperand = new Fraction(7, 8);
     result = firstOperand.subtract(secondOperand);
     System.out.println("The difference of " + firstOperand  +
           " and " +  secondOperand + " is \t" + result);
     // 15/-2 * 1/4
     firstOperand = new Fraction(15, -2);
     result = firstOperand.multiply(oneFourth);
     System.out.println("The product of " + firstOperand  +
           " and " +  oneFourth + " is \t" + result);
     // (-21/2) / (3/7)
     firstOperand = new Fraction(-21, 2);
     secondOperand= new Fraction(3, 7);
     result = firstOperand.divide(secondOperand);
     System.out.println("The quotient of " + firstOperand  +
           " and " +  secondOperand + " is \t" + result);
     // -21/2 + 7/8
     firstOperand = new Fraction(-21, 2);
     secondOperand= new Fraction(7, 8);
     result = firstOperand.add(secondOperand);
     System.out.println("The sum of " + firstOperand  +
           " and " +  secondOperand + " is \t\t" + result);
               // 0/10, 5/(-15), (-22)/7
     firstOperand = new Fraction(0, 10);
               doubleResult = firstOperand.toDouble();
     System.out.println("The double floating point value of " + firstOperand  + " is \t" + doubleResult);
     firstOperand = new Fraction(1, -3);
               doubleResult = firstOperand.toDouble();
     System.out.println("The double floating point value of " + firstOperand  + " is \t" + doubleResult);
     firstOperand = new Fraction(-22, 7);
               doubleResult = firstOperand.toDouble();
     System.out.println("The double floating point value of " + firstOperand  + " is \t" + doubleResult);
     System.out.println("\n=========================================");
     firstOperand = new Fraction(-21, 2);
     System.out.println("First = " + firstOperand);
     // equality check
     System.out.println("check First equals First: ");
     if (firstOperand.equals(firstOperand))
        System.out.println("Identity of fractions OK");
     else
        System.out.println("ERROR in identity of fractions");
     secondOperand = new Fraction(-42, 4);
     System.out.println("\nSecond = " + secondOperand);
     System.out.println("check First equals Second: ");
     if (firstOperand.equals(secondOperand))
        System.out.println("Equality of fractions OK");
     else
        System.out.println("ERROR in equality of fractions");
     // comparison check
     Fraction first = (Fraction)firstOperand;
     Fraction second = (Fraction)secondOperand;
    Â
     System.out.println("\ncheck First compareTo Second: ");
     if (first.compareTo(second) == 0)
        System.out.println("Fractions == operator OK");
     else
        System.out.println("ERROR in fractions == operator");
     second = new Fraction(7, 8);
     System.out.println("\nSecond = " + second);
     System.out.println("check First compareTo Second: ");
     if (first.compareTo(second) < 0)
        System.out.println("Fractions < operator OK");
     else
        System.out.println("ERROR in fractions < operator");
     System.out.println("\ncheck Second compareTo First: ");
     if (second.compareTo(first) > 0)
        System.out.println("Fractions > operator OK");
     else
        System.out.println("ERROR in fractions > operator");
     System.out.println("\n=========================================");
     System.out.println("\ncheck FractionException: 1/0");
     try {
        Fraction a1 = new Fraction(1, 0);       Â
     }
     catch ( FractionException fe )
            {
                  System.err.printf( "Exception: %s\n", fe );
            } // end catch
     System.out.println("\ncheck FractionException: division");
     try {
        Fraction a2 = new Fraction();       Â
        Fraction a3 = new Fraction(1, 2);       Â
        a3.divide(a2);
     }
     catch ( FractionException fe )
            {
                  System.err.printf( "Exception: %s\n", fe );
            } // end catch
  }  // end main
} // end Fraction
**********************************************************************************************************************
/* This file specifies methods for FractionInterface     */
/* Do not modify this file!!                         */
package PJ1;
public interface FractionInterface {
  /**
  * Task: convert a fraction to double value
  *
  * @return the double floating point value of a fraction
  */
  public double toDouble();
  /**
  * Task: Adds two fractions.
  *
  * @param secondFraction
  *           a fraction that is the second operand of the addition
  * @return a fraction which is the sum of the invoking fraction and the
  *        secondFraction
  */
  public FractionInterface add(FractionInterface secondFraction);
  /**
  * Task: Subtracts two fractions.
  *
  * @param secondFraction
  *           a fraction that is the second operand of the subtraction
  * @return a fraction which is the difference of the invoking fraction and
  *        the second operand
  */
  public FractionInterface subtract(FractionInterface secondFraction);
  /**
  * Task: Multiplies two fractions.
  *
  * @param secondFraction
  *           a fraction that is the second operand of the multiplication
  * @return a fraction which is the product of the invoking fraction and the
  *        secondFraction
  */
  public FractionInterface multiply(FractionInterface secondFraction);
  /**
  * Task: Divides two fractions.
  *
  * @param secondFraction
  *           a fraction that is the second operand of the division
  * @return a fraction which the quotient of the invoking fraction and the
  *        secondFraction
  * @throws FractionException
  *            if secondFraction=0
  */
  public FractionInterface divide(FractionInterface secondFraction);
  /**
  * Task: Get's the fraction's reciprocal
  *
  * @return the reciprocal of the invoking fraction
  * @throws FractionException
  *            if the new number with denominator=0
  */
  public FractionInterface getReciprocal();
}
*******************************************************************************************************************
/************************************************************************************
* Do not modify this file.
* FractionException class. It is used by Fraction class
*************************************************************************************/
package PJ1;
public class FractionException extends RuntimeException {
  public FractionException() {
     this("");
  }
  public FractionException(String errorMsg) {
     super(errorMsg);
  }
}
**************************************************************************************************************
package PJ1;
/* This program is used to test PJ1.Fraction class
*/
import java.util.Scanner;
class PJ1_Test {
  static private Scanner scanner;
  private static Fraction readFraction() {
     System.out.print("\nTry to read a fraction x/y, please enter x y : ");
     int numerator = scanner.nextInt();
     int denominator = scanner.nextInt();
     Fraction f = new Fraction(numerator, denominator);
     System.out.println("\t\tRead OK:" + f);
     return f;
  }
  private static void printOperations() {
     System.out.println("==============================================");
     System.out.println("\nOperations:");
     System.out
           .println(" 0) exit \t1) add \t\t2) subtract \t3) multiply \t4) divide");
     System.out
           .println(" \t\t5) compareTo \t6) equals \t7) recipocal \t8) toDouble ");
     System.out.print("\nEnter an operation number: ");
  }
  public static void main(String args[]) {
     scanner = new Scanner(System.in); // scanner for input
     boolean continueLoop = true; // determines if more input is needed
     Fraction n1 = null;
     Fraction n2 = null;
     int op, x, y;
     do {
        try // read two numbers and calculate quotient
        {
           printOperations();
           op = scanner.nextInt();
           if (op == 0) {
              break;
           } else if ((op > 0) && (op < 7)) {
              n1 = readFraction();
              n2 = readFraction();
           } else if ((op > 6) && (op < 9)) {
              n1 = readFraction();
           } else {
              System.out.print("\nInvalid input... try again\n");
              continue;
           }
           System.out.println("\nTests:\n");
           switch (op) {
           case 1:
              System.out.println("\t" + n1 + " + " + n1 + " = "
                    + n1.add(n1));
              System.out.println("\t" + n2 + " + " + n2 + " = "
                    + n2.add(n2));
              System.out.println("\t" + n1 + " + " + n2 + " = "
                    + n1.add(n2));
              System.out.println("\t" + n2 + " + " + n1 + " = "
                    + n2.add(n1));
              break;
           case 2:
              System.out.println("\t" + n1 + " - " + n1 + " = "
                    + n1.subtract(n1));
              System.out.println("\t" + n2 + " - " + n2 + " = "
                    + n2.subtract(n2));
              System.out.println("\t" + n1 + " - " + n2 + " = "
                    + n1.subtract(n2));
              System.out.println("\t" + n2 + " - " + n1 + " = "
                    + n2.subtract(n1));
              break;
           case 3:
              System.out.println("\t" + n1 + " * " + n1 + " = "
                    + n1.multiply(n1));
              System.out.println("\t" + n2 + " * " + n2 + " = "
                    + n2.multiply(n2));
              System.out.println("\t" + n1 + " * " + n2 + " = "
                    + n1.multiply(n2));
              System.out.println("\t" + n2 + " * " + n1 + " = "
                    + n2.multiply(n1));
              break;
           case 4:
              System.out.println("\t" + n1 + " / " + n1 + " = "
                    + n1.divide(n1));
              System.out.println("\t" + n2 + " / " + n2 + " = "
                    + n2.divide(n2));
              System.out.println("\t" + n1 + " / " + n2 + " = "
                    + n1.divide(n2));
              System.out.println("\t" + n2 + " / " + n1 + " = "
                    + n2.divide(n1));
              break;
           case 5:
              System.out.println("\t" + n1 + " ct " + n1 + " = "
                    + n1.compareTo(n1));
              System.out.println("\t" + n2 + " ct " + n2 + " = "
                    + n2.compareTo(n2));
              System.out.println("\t" + n1 + " ct " + n2 + " = "
                    + n1.compareTo(n2));
              System.out.println("\t" + n2 + " ct " + n1 + " = "
                    + n2.compareTo(n1));
              break;
           case 6:
              System.out.println("\t" + n1 + " eq " + n1 + " = "
                    + n1.equals(n1));
              System.out.println("\t" + n2 + " eq " + n2 + " = "
                    + n2.equals(n2));
              System.out.println("\t" + n1 + " eq " + n2 + " = "
                    + n1.equals(n2));
              System.out.println("\t" + n2 + " eq " + n1 + " = "
                    + n2.equals(n1));
              break;
           case 7:
              System.out.println("\t" + n1 + " getReciprocal= "
                    + n1.getReciprocal());
              break;
           case 8:
              System.out.println("\t" + n1 + " toDouble = "
                    + n1.toDouble());
              break;
           }
        } // end try
        catch (FractionException fracitonException) {
           System.err.printf("\nFraction Exception: %s\n",
                 fracitonException);
        } // end catch
     } while (continueLoop); // end do...while
  } // end main
} // end class
Hel-----------lo -----------Sir-----------/Ma-----------dam-----------Tha-----------nk -----------You----------- fo-----------r u-----------sin-----------g o-----------ur -----------web-----------sit-----------e a-----------nd -----------and----------- ac-----------qui-----------sit-----------ion----------- of----------- my----------- po-----------ste-----------d s-----------olu-----------tio-----------n.P-----------lea-----------se -----------pin-----------g m-----------e o-----------n c-----------hat----------- I -----------am -----------onl-----------ine----------- or----------- in-----------box----------- me----------- a -----------mes-----------sag-----------e I----------- wi-----------ll