Member Avatar for Amoryethel

I'm in the works of creating a program that dishes out basic arithmetics with fractions, i.e., add, subtract. However, I found myself stumped over this error.

Test.java:18: 'void' type not allowed here
System.out.println(r1.add(r2));
^
1 error

My code is as follows:

\\ The constructor \\
public class RationalNumber
{
	int num;
	int den;
	
	private int gcd(int x, int y)
	{
		while(y != 0)
		{
			int temp = x % y;
			x = y;
			y = temp;
		} 		
		return x;
	}
	
	public RationalNumber(int numerator, int denominator)
	{
		if(denominator == 0)
		{
			throw new IllegalArgumentException("You can't divide by zero.");
		}
		else
		{
			num = numerator;
			den = denominator;
		}
	}
	
	public RationalNumber()
	{
		this (0,1); 
	}
	
	public boolean equals(Object o)
	{
		if (o instanceof RationalNumber)
		{
			RationalNumber other = (RationalNumber) o;
			int r1 = this.gcd(num,den);
			int r2 = this.gcd(other.getNumerator(),other.getDenominator());
			return num/r1 == other.num/r2 && den/r1 == other.den/r2;	
		}
		else
		{
			return false;
		}
	}
	
	public int getDenominator()
	{
		return den;
	}
	
	public int getNumerator()
	{
		return num;
	}
	
	public void add(RationalNumber r1)
	{
		int commonDen = den * r1.getDenominator();
		int num1 = num * r1.getDenominator();
		int num2 = r1.getNumerator() * den;
		int sum = num1 + num2;
	}
	
	public void sub(RationalNumber r1)
	{
      int commonDen = den * r1.getDenominator();
		int num1 = num * r1.getDenominator();
		int num2 = r1.getNumerator() * den;
		int sum = num1 - num2;
	}
	
	public String toString()
	{
		if (den == 1)
		{
			return num + "";
		}
		else	
		{
			return num + "/" + den;
		}
	}
}
\\ The client code \\
public class Test
{
   public static void main (String[] args)
   {
		RationalNumber r1 = new RationalNumber(1,3);
		RationalNumber r2 = new RationalNumber(1,6);
		
		System.out.println(r1.add(r2));
	}
}

What is it I must do to rid myself of this problem? Also is my add and subtract methods correct?

System.out.println()

will try to print anything inside the parentheses.

But as you can see your

r1.add(r2)

is a method that returns void.

You cannot print a 'void'.

if you want to show the result of r1.add(r2) the you need to change the return parameter of your add method. try

public int add(RationalNumber r2) {

// then add the bottom of your method you add a return statement

return sum;
}

this will return your sum and then you can print it using system.out.

(",)

Member Avatar for Amoryethel

Thank you very much. That solved the compile error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.