userb
userb

Reputation: 173

Object Oriented Programming with said methods. Java

Rational numbers contain an integer numerator and denominator. Write the code to implement a class named Rational which stores two private ints (numer and denom) with the following methods:

public Rational(int,int)
constructor that sets the numer and denom

public Rational(Rational)

//copy constructor for a Rational object

public void setNumer(int) //sets the numerator to the paramter value

public int getNumer()
//returns the stored numerator

public void setDenom(int) //sets the denominator to the paramter value

public int getDenom() //returns the stored denominator

//return a new Rational object that contains the reciprocal of the object that invokes the method.

public Rational reciprocal()

//returns a new Rational object that contains the product of the two paramteres.

public static Rational multiply(Rational a, Rational b)


I am stuck at the 7th method for this class. I don't understand how to flip the numbers so that they are reciprocals. Any help will be greatly Appreciated. This is my code so far:

class Rational {
    private int numer;
    private int denom;

    public Rational(int numer, int denom){
        this.numer = numer;
        this.denom = denom;
    }

    public Rational(Rational rational){
        rational = new Rational(numer, denom);
    }

    public void setNumber(int fum){
        numer = fum;
    }

    public int getNumber(){
        return 5;
    }

    public void setDenom(int Dum){
        denom = Dum;
    }

    public int getDenom(){
        return 10;
    }

    public Rational reciprocal(){
        ;
    }
}



public class Results {
    public static void main(String[] args){

    }

}

Upvotes: 2

Views: 970

Answers (3)

Forseth11
Forseth11

Reputation: 1438

Try this:

public Rational reciprocal(){
  return new Rational(denom, numer);
}

It get the reciprocal which is just the numerator and denominator flipped. return new Rational(denom, numer); does this by creating a new rational instance with the denominator from the current one as the numerator and as the numerator as the current instance as the denominator.

Really a reciprocal is one divided by the original number as said here, but flipping the numerator and denominator does the same thing as dividing by its self.

Upvotes: 0

Diego Montoya
Diego Montoya

Reputation: 139

You have to return a new Rational with the numbers fliped.

public Rational reciprocal(){
    return new Rational(this.denom,this.numer);
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

Math is Fun: Reciprocal of a Fraction says (in part) to get the reciprocal of a fraction, just turn it upside down.

public Rational reciprocal(){
    return new Rational(this.denom, this.number);
}

Upvotes: 3

Related Questions