AntonioEsp
AntonioEsp

Reputation: 33

Fraction class cannot be applied to given types?

code throws the following error: method greatestCommonDivisor in class Fraction cannot be applied to given types; and then follows with

required: int,int found: no arguments reason: actual and formal argument lists differ in length

I am not so sure why the error is there, I tried changing a few things with no luck


class Fraction{
    private int numerator;
    private int denominator;

    public Fraction(int _num1, int _num2){
        numerator = _num1;
        denominator = _num2;
    }

    public int greatestCommonDivisor(int num1, int num2){
        int greatestCommon = 1;
        for(int i = 1; i <= num1 && i <= num2; i++){
            if(num1 % i == 0 && num2 % i == 0)
            greatestCommon = i;}
            return greatestCommon;
        }
}

public class testing2
{
    public static void main(String[] arg)
    {
        Scanner in = new Scanner(System.in);

        int num11 = in.nextInt();
        int num22 = in.nextInt();

        Fraction gcd = new Fraction(num11, num22);
        System.out.println(gcd.greatestCommonDivisor());
    }
}

Upvotes: 0

Views: 492

Answers (2)

the reason in quite simple:

you have to call the method like this

System.out.println(gcd.greatestCommonDivisor(num11, num22));

why?

because your method is defined as

int greatestCommonDivisor(int num1, int num2)

so,just pass the parameters you read using the scanner and you are done! :)

Upvotes: 2

Mushif Ali Nawaz
Mushif Ali Nawaz

Reputation: 3866

Probably the greatestCommonDivisor() method should look like this:

public int greatestCommonDivisor() {
    int greatestCommon = 1;
    for (int i = 1; i <= numerator && i <= denominator; i++) {
        if (numerator % i == 0 && denominator % i == 0)
            greatestCommon = i;
    }
    return greatestCommon;
}

You are not using the member variables of Fraction class (provided in the constructor) here. And I would suggest renaming the numerator and denominator variable names to more accurate names like: firstNumber and secondNumber etc.

Upvotes: 2

Related Questions