Java问题调用方法的实例?

时间:2013-02-01 17:40:42

标签: java class

我创建了一个设计用于获取2个分数的类,每个分数都带有分子和分母并添加它们,输出另一个分数。

当我编译程序时,我遇到了一个问题:

Fraction F3 = new Fraction.add(F1,F2); 主要方法

错误:未找到类型分数$ add

如果我将一个类编译为程序将运行,但我希望所有方法都严格地在Fraction类中并调用UseFraction类中的分数。

import java.io.*;
import java.util.*;
import java.text.*;


public final class Fraction
{
    private int numerator, denominator;

    public Fraction (int numerator, int denominator) throws IllegalArgumentException
    {
        this.numerator = numerator;

        if (denominator == 0)
        {
            throw new IllegalArgumentException ();
        }
        this.denominator = denominator;
    }


    //As an instance method
    public void add (Fraction F)
    {
        this.numerator = this.numerator * F.denominator + this.denominator * F.numerator;
        this.denominator = this.numerator * this.denominator;
    }


    //As a static method
    public static Fraction add (Fraction F1, Fraction F2)
    {
        return new Fraction (F1.numerator * F2.denominator + F1.denominator * F2.numerator, F1.numerator);
    }


    //@ Override
    public String toString ()
    {
        return (this.numerator + "/" + this.denominator);
    }

}



public class UseFraction 
{

    public static void main (String str[]) throws IOException
    {
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));

        Fraction F1 = new Fraction (5, 7); // first fraction constructor
        Fraction F2 = new Fraction (3, 8); // second fraction constructor
        Fraction F3 = new Fraction.add (F1, F2); // addition

        System.out.println ("The sum is " + F3); 

    }
}

3 个答案:

答案 0 :(得分:3)

使用Fraction.add(F1, F2),而不是new Fraction.add

答案 1 :(得分:1)

Fraction F3 = new Fraction.add (F1, F2); // addition

这应该只是:

Fraction F3 = Fraction.add (F1, F2); // addition

答案 2 :(得分:0)

Fraction F3 = new Fraction.add (F1, F2);

将其更改为:

Fraction F3 = Fraction.add (F1, F2);