我的Fraction程序中的错误(Java)

时间:2015-10-04 14:57:21

标签: java

大家好我正在用Java编写一个分数程序。当我运行程序时,我得到以下错误。

Exception in thread "main" java.lang.ArithmeticException
   at PJ1.Fraction.setFraction(Fraction.java:63)
   at PJ1.Fraction.<init>(Fraction.java:55)
   at PJ1.Fraction.add(Fraction.java:89)
   at PJ1.Fraction.main(Fraction.java:238)

我不确定错误发生的位置/原因。

    package PJ1;

public class Fraction implements FractionInterface, Comparable<Fraction>
{
   private   int numerator;  
   private   int denominator;  

   public Fraction()
   {
       // set fraction to default = 0/1
       setFraction(0,1);
   }   // end default constructor

   public Fraction(int num, int den)
   {
       // implement this method!
       setFraction(num,den);
   }   // end constructor

   public void setFraction(int num, int den)
   {
       // implement this method!
       // return FractionException if initial Denominator is 0
       if(den==0)
           throw new ArithmeticException();
       if(den<0){
       if(num<0){
           den *=-1;
           num *=-1;
       }
       else{
           den*=-1;
           num*=-1;

       }
       }
   }   // end setFraction

   public double toDouble()
   {
       // return double floating point value
       // implement this method!
       return (double) numerator / denominator;
   }   // end toDouble

   public FractionInterface add(FractionInterface aFraction)
   {
// return a new Fraction object
// a/b + c/d is (ad + cb)/(bd)
// implement this method!
       Fraction z = new Fraction((numerator *((Fraction)aFraction).denominator) +
               (denominator *((Fraction)aFraction).numerator),
               denominator * ((Fraction)aFraction).denominator);
       z.reduceFractionToLowestTerms();
       return z;
   }   // end add

   public FractionInterface subtract(FractionInterface aFraction)
   {
// return a new Fraction object
// a/b - c/d is (ad - cb)/(bd)
// implement this method!
       Fraction z = new Fraction((numerator *((Fraction)aFraction).denominator) -
               (denominator *((Fraction)aFraction).numerator),
               denominator * ((Fraction)aFraction).denominator);
       z.reduceFractionToLowestTerms();
       return z;
   }   // end subtract

   public FractionInterface multiply(FractionInterface aFraction)
   {
// return a new Fraction object
// a/b * c/d is (ac)/(bd)
// implement this method!
       Fraction z = new Fraction((numerator *((Fraction)aFraction).denominator) *
               (denominator *((Fraction)aFraction).numerator),
               denominator * ((Fraction)aFraction).denominator);
       z.reduceFractionToLowestTerms();
       return z;

   }   // end multiply

   public FractionInterface divide(FractionInterface aFraction)
   {
// return a new Fraction object
// return FractionException if aFraction is 0
// a/b / c/d is (ad)/(bc)
// implement this method!
       Fraction z = new Fraction((numerator *((Fraction)aFraction).denominator) /
               (denominator *((Fraction)aFraction).numerator),
               denominator * ((Fraction)aFraction).denominator);
       z.reduceFractionToLowestTerms();
       return z;
       }   // end divide

   public FractionInterface getReciprocal()
   {
// return a new Fraction object
// return FractionException if new Fraction is 0
// implement this method!
       if(numerator ==0)
           throw new ArithmeticException();
       return new Fraction(denominator, numerator);

   } // end getReciprocal


   public boolean equals(Object other)
   {
// implement this method!
       ((Fraction)other).reduceFractionToLowestTerms();
       return (numerator == ((Fraction)other).numerator) && (denominator == ((Fraction)other).denominator);

   } // end equals


   public int compareTo(Fraction other)
   {
// implement this method!
       if(toDouble() > other.toDouble()){
           return 2;
       }
       else if(toDouble() < other.toDouble()){
           return -2;
           }
       else{
           return 0;
       } }
       // end compareTo


   public String toString()
   {
       return numerator + "/" + denominator;
   } // end toString

下面列出了我不应该修改的其他代码。

private void reduceFractionToLowestTerms()
   {
// implement this method!
//
// Outline:
// compute GCD of numerator & denominator
// GCD works for + numeratorbers.
// So, you should eliminate - sign
// then reduce numeratorbers : numerator/GCD and denominator/GCD
       boolean neg = false;
       if(numerator== -1){
           numerator *= -1;
           neg = true;
       }
       int gcd = GCD(Math.abs(numerator), Math.abs(denominator));

       numerator = numerator / gcd;
       denominator = denominator / gcd;
       if(neg==true){
           numerator *=-1;
       }
   }   // end reduceFractionToLowestTerms

   /** Task: Computes the greatest common divisor of two integers.
   * @param integerOne   an integer
   * @param integerTwo   another integer
   * @return the greatest common divisor of the two integers */
   private int GCD(int integerOne, int integerTwo)
   {
       int result;

       if (integerOne % integerTwo == 0)
           result = integerTwo;
       else
           result = GCD(integerTwo, integerOne % integerTwo);

       return result;
   }   // end GCD


   //-----------------------------------------------------------------
   // 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=========================================\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);
       System.out.println("\tExpected result :\t\t23/16\n");

       // 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);
       System.out.println("\tExpected result :\t\t-5/16\n");


       // 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);
       System.out.println("\tExpected result :\t\t-15/8\n");

       // (-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);
       System.out.println("\tExpected result :\t\t-49/2\n");

       // -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);
       System.out.println("\tExpected result :\t\t-77/8\n");


// 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);
       System.out.println("\tExpected result \t\t\t0.0\n");
       firstOperand = new Fraction(1, -3);
doubleResult = firstOperand.toDouble();
       System.out.println("The double floating point value of " + firstOperand   + " is \t" + doubleResult);
       System.out.println("\tExpected result \t\t\t-0.333333333...\n");
       firstOperand = new Fraction(-22, 7);
doubleResult = firstOperand.toDouble();
       System.out.println("The double floating point value of " + firstOperand   + " is \t" + doubleResult);
       System.out.println("\tExpected result \t\t\t-3.142857142857143");
       System.out.println("\n=========================================\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);      
       System.out.println("Error! No FractionException");
       }
       catch ( FractionException fe )
    {
       System.err.printf( "Exception: %s\n", fe );
    } // end catch
       System.out.println("Expected result : FractionException!\n");

       System.out.println("\ncheck FractionException: division");
       try {
           Fraction a2 = new Fraction();      
           Fraction a3 = new Fraction(1, 2);      
           a3.divide(a2);
       System.out.println("Error! No FractionException");
       }
       catch ( FractionException fe )
    {
       System.err.printf( "Exception: %s\n", fe );
    } // end catch
       System.out.println("Expected result : FractionException!\n");

   }   // end main
} // end Fraction

These are the following parts that I am given but I am not supposed to Modify.

/************************************************************************************
* 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);
    }

    }

* This file specifies methods for FractionInterface       */
/* Do not modify this file!!             */

package PJ1;

public interface FractionInterface
{
/** Task: Sets a fraction to a given value.
* @param num is the integer numerator
* @param den is the integer denominator
* @throws ArithmeticException if denominator is 0 */
public void setFraction(int num, int den);

   /** Task: convert a fraction to double value
   * @return the double floating point value of a fraction */
   public double toDouble();


   /** Task: Adds two fractions.
   * @param aFraction is a fraction that is the second operand of the addition
   * @return a fraction which is the sum of the invoking fraction and the aFraction */
   public FractionInterface add(FractionInterface aFraction);



   /** Task: Subtracts two fractions.
   * @param aFraction 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 aFraction);

   /** Task: Multiplies two fractions.
   * @param aFraction a fraction that is the second operand of the multiplication
   * @return a fraction which is the product of the invoking fraction and the aFraction*/
   public FractionInterface multiply(FractionInterface aFraction);

   /** Task: Divides two fractions.
   * @param aFraction a fraction that is the second operand of the division
   * @return a fraction which the quotient of the invoking fraction and the aFraction
* @throws FractionException if aFraction is 0 */
   public FractionInterface divide(FractionInterface aFraction);

   /** Task: Get's the fraction's reciprocal
   * @return the reciprocal of the invoking fraction
* @throws FractionException if the new number with denominator is 0*/
   public FractionInterface getReciprocal();

}

1 个答案:

答案 0 :(得分:0)

  

我不确定错误发生的位置/原因。

当你的堆栈跟踪告诉它时, 在Fraction.java的第63行抛出异常, 这一定是它:

   if(den==0)
       throw new ArithmeticException();

不要以0为分母来调用此函数。