Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: Suppose we want to implement a rational number class called Rational. Each

ID: 3844793 • Letter: J

Question

JAVA:

Suppose we want to implement a rational number class called Rational.

Each object of Rational represents a rational number with an integer numerator and a nonzero integer denominator.

The instance variables of Rational corresponding to the numerator and denominator are int n and int d.

Implement the two-parameter Rational constructor :

public Rational (int n, int d) { }

The constructor should initialize this.n and this.d to the Rational object representing rational number n/d. Make sure to reduce n and d to lowest terms.

Also, to normalize the sign, only this.n is allowed to be negative, not this.d. For example, 4/-5 would be represented by -4/5 and -4/-5 would be represented by 4/5.

If 0 is passed in for d, then throw an ArithmeticException with the message "Can't divide by zero."    (Don't forget the period at the end.)

If 0 is passed in for n and d is nonzero then the resulting values for this.n and this.d should be 0 and 1 respectively.

Explanation / Answer

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package javaapplication2;

/**
*
* @author Namburi Ramesh
*/
public class Rational {
public int n,d;

//constructor
public Rational(int n, int d) {
if(d==0){
throw new ArithmeticException("Can't divide by zero.");
}else if(n==0){
this.n=0;
this.d=1;
}else{
  
//find the greatest common divisor and divide numerator and denominator with gcd to reduce them to lower terms
int g=gcd(n,d);
if(g<0){
g=-g;
}
if(n<0 && d<0){
this.n=-n/g;
this.d=-d/g;
}else if(n>0 && d<0){
this.n=-n/g;
this.d=-d/g;
}else{
this.n=n/g;
this.d=d/g;
}
}
}

//function to return greatest common divisor of two numbers
private int gcd(int n, int d) {
if(d==0){
return n;
}else{
return gcd(d,n%d);
}
}
  
}