首页 > 解决方案 > 我该如何解决预期错误?

问题描述

我正在编写一个函数,该函数将另一个类中构造的对象用作变量。这是代码,我在这里得到错误“commonDenominator(Fraction,Fraction)”,Fraction和Fraction中预期的标识符的两个错误。

public class MyMath {

 public static int commonDenominator(Fraction,Fraction){ 
                                                                               
       int d1 = getDenominator();                              
       int d2 = getDenominator();
       if (d1%d2==0){
          return d1; 
        } else if (d2%d1=0){
          return d2;
        } else {
         return d1*d2 ; 
        } 
  } 
} 

另一方面,这是分数类的代码:

public class Fraction {

    // The fields of this Fraction
    private int numerator;
    private int denominator;
  
    /** Constructs a fraction.
     *  The newly constructed fraction is reduced.
     *  For example, given 6 and 9, constructs the fraction 2/3.
     *  If the denominator is negative, converts the signs of both the numerator and the denominator.
     *  For example, 2/-3 becomes -2/3, and -2/-3 becomes 2/3.     
     *  @param numerator   can be signed
     *  @param denominator can be signed
     */
    public Fraction (int numerator, int denominator) {
        // Handles the signs of the numerator and denominator
        if (denominator < 0) {
            numerator = numerator * -1;
            denominator = denominator * -1;
        }
        // Initializes the object's fields
        this.numerator = numerator;
        this.denominator = denominator;
        // Divides the numerator and denominator by their greatest common divisor
        
    }

    /** Constructs a random fraction.
     *  The denominator is a random positive random number which is less than limit, and
     *  the numerator is a random positive random number which is less than the denominator.
     *  @param limit must be greater or equal to 1
     */
    public Fraction(int limit) {
        // Put your code here
        int denominator1 = (int)(Math.random()*(limit+1)); 
        int numerator1 = (int)(Math.random()*(denominator + 1)); 
        this.numerator = numerator1;
        this.denominator = denominator1;
    }

    /** Returns the numerator of this fraction.
     *  @return the numerator of this fraction
     */
    public int getNumerator() {
        return numerator;
    }

    /** Returns the denominator of this fraction.
     *  @return the denominator of this fraction
     */
    public int getDenominator() {
        return denominator;
    }
}

标签: javaobjectidentifier

解决方案


您需要命名该方法的参数。可推测的,d1并且d2应该分别是它们的分母:

public static int commonDenominator(Fraction f1, Fraction f2) { 
   // Here ----------------------------------^------------^
   int d1 = f1.getDenominator(); // Use f1
   int d2 = f2.getDenominator(); // Use f2
   if (d1%d2==0){
      return d1; 
    } else if (d2%d1=0){
      return d2;
    } else {
     return d1*d2 ; 
    } 
} 

推荐阅读