user13304959
user13304959

Reputation: 11

Doing a course on Code HS, errors say "Bad operator types for binary operator" for lines with the public void. Not sure what I'm doing wrong

EXERCISE DIRECTIONS

In this exercise, you must take your Fraction class from earlier and extend it by adding a few handy methods.

public void add(Fraction other)
public void subtract(Fraction other)
public void multiply(Fraction other)
public int getNumerator();
public int getDenominator();
public void setNumerator(int x);
public void setDenominator(int x);
public String toString();

Use the FractionTester file to test as you go along.

Note that

public void add(Fraction other)
public void subtract(Fraction other)
public void multiply(Fraction other)

are void methods. They do not return anything. These methods should not create a new Fraction and return it.

Instead, these methods should modify the instance variables to be added, subtracted, or multiplied by the Fraction other.

For example, the following code:

Fraction first = new Fraction(1, 2);
Fraction second = new Fraction(1, 3);
System.out.println();

System.out.println("BEFORE:");
System.out.println("first: " + first);
System.out.println("second: " + second);

first.multiply(second);

System.out.println("AFTER:");

System.out.println("first: " + first);
System.out.println("second: " + second);

Should print out:

BEFORE: first: 1 / 2 second: 1 / 3

AFTER: first: 1 / 6 second: 1 / 3 The Fraction first was modified by being multiplied by the Fraction second. first was affected, second was not. 1/2 became 1/6 because it was multiplied by 1/3.

This is my code:

public class Fraction
{
    // Create your instance variables and constructor here

    //Instance variables
    private int num;
    private int den;

    //Constructor
    public Fraction(int nume, int dene)
    {
        num = nume;
        den = dene;
    }


    public void add(Fraction other) 
    {
        Fraction a = num/den + other;
    }

    public void subtract(Fraction other) 
    {
        Fraction b = num/den - other;
    }

    public void multiply(Fraction other) 
    {
        Fraction c = num/den * other;
    }

    public String toString() 
    {
        return "";
    }
}

Upvotes: 1

Views: 450

Answers (1)

WJS
WJS

Reputation: 40057

You can't multiply an int (e.g. den or num) directly by a Fraction object. You need to dereference the passed fraction argument and then update the den and num components of the calling instance.

This


public void multiply(Fraction other)  {
        Fraction c = num/den * other;
 }

Needs to be replaced with this.

public void multiply(Fraction other)  {
        num = num * other.num;
        den = den * other.den;
 }

When you add or subtract, you need to find common denominators.

Upvotes: 1

Related Questions