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?