Question

This is a continuation of a question I posted last week that I'm still having trouble with. I'm trying to write a Rational class containing two private instance variables num and den whose datatype is BigInteger. The Rational constructor takes two int's as their parameters.

My problem is whenever I write the add or multiply method in my Rational class Eclipse gives me an error. I don't know why it give me an error. As I understand it, the operators +, -, *, / can only be used on primitive datatypes and since my private instance variables are BigInteger's they are nonpprimitive datatypes and any addition or multiplication will have to be done through the add or multiply method.

The code below gives me an error but I don't know why. I don't understand what's conceptually wrong with the code. Is the reason for the error something conceptual with using this.num/this.den/r.num/r.den in the methods or does the error have to do with something related to syntax? The error for the add and multiply methods are the same and it says "The constructor Rational(BigInteger,BigInteger) is undefined".

public class Rational{


  public Rational(int x, int y) {
      num = BigInteger.valueOf(x);
      den = BigInteger.valueOf(y);
 }

  public Rational add(Rational r) {
     return new Rational(this.num.multiply(r.den).add(r.num.multiply(this.den)), this.den.multiply(r.den));
}

 public Rational multiply(Rational r) {
      return new Rational(this.num.multiply(r.num), this.den.multiply(r.den));
}


private BigInteger num;
private BigInteger den
}
Was it helpful?

Solution

The constructor you have defined, takes 2 ints as arguments.

 public Rational(int x, int y) {
      num = BigInteger.valueOf(x);
      den = BigInteger.valueOf(y);
 }

and the compiler complains because you are passing two BigIntegers.

Have a new overloaded Constructor

 public Rational(BigInteger x, BigInteger y) {
      num = x;
      den = y;
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top