Boris4ka
Boris4ka

Reputation: 93

Java fraction addition

I've done hours of searching on this problem and can't come up with a solution:

public FractionInterface add(FractionInterface operand) {

    int numerator = num*operand.den + operand.num*den;
    int denominator = den*operand.den;

    return new Fraction(numerator, denominator);

}

Every example I've found so far has it done this way, but when I try to do it this way, it doesn't compile and gives this error three times for each operand.*:

error: cannot find symbol
            int numerator = num*operand.den + operand.num*den;
                                       ^
symbol:   variable den
location: variable operand of type FractionInterface

num and den are the private ints. What am I doing wrong? Should I post the entire program? This is a homework problem, so it must be done using this type of method.

Upvotes: 0

Views: 1598

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234795

I assume that FractionInterface is an interface. The actual class of operand is unknown—in particular, it may not even have member fields num and den. (You are not allowed to assume it is an instance of Fraction.)

Interface FractionInterface should define accessor methods to retrieve the value of the numerator and denominator. Use those to get the values you need from operand.

Upvotes: 0

vicatcu
vicatcu

Reputation: 5837

I believe in order for you to be able to access the den and num members of the operand argument, they must be declared public or protected.

Upvotes: 0

Prashant Kumar
Prashant Kumar

Reputation: 22529

You need to access the private num and den using the public accessor methods.

If the respective accessor methods are getNum() and getDen()

public FractionInterface add(FractionInterface operand) {

    int numerator = num*operand.getDen() + operand.getNum()*den;
    int denominator = den*operand.getDen();

    return new Fraction(numerator, denominator);
}

Upvotes: 3

Related Questions