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

Write a Java class Rational that is intended to store a rational number represen

ID: 3800524 • Letter: W

Question

Write a Java class Rational that is intended to store a rational number represented in the form numerator / denominator, where numerator and denominator are integers. The class must have a constructor accepting two integers, a public method getNumber that returns a floating-point representation of the stored rational number, and a public method sqrt for computing the square root of the represented rational number (as a floating-point value). Your class constructor and sqrt method must throw a custom exception if the operation is impossible. Provide a test class with main() method that handles the thrown exceptions and reports them to the user.

Explanation / Answer

HI, Please find my implementation.

Please let me know in case of any issue.

public class Rational {

  

   // instance variable

   private int numerator;

   private int denominator;

  

   public Rational(int numerator, int denominator) {

      

       if(denominator == 0)

           throw new IllegalArgumentException("Denominator can not be zero");

       this.numerator = numerator;

       this.denominator = denominator;

   }

   public int getNumerator() {

       return numerator;

   }

  

   public int getDenominator() {

       return denominator;

   }

  

   public void setNumerator(int numerator) {

       this.numerator = numerator;

   }

  

   public void setDenominator(int denominator) {

       this.denominator = denominator;

   }

  

   public double getNumber(){

       return (double)numerator/(double)denominator;

   }

  

   public double sqrt(){

       return Math.sqrt(getNumber());

   }

  

   @Override

   public String toString() {

       return numerator+"/"+denominator;

   }

}

#####################

public class RationalTest {

  

   public static void main(String[] args) {

      

       // Creating Rational object

       Rational r1 = new Rational(4, 7);

      

       System.out.println(r1);

      

       System.out.println("Number: "+r1.getNumber());

   }

}

/*

Sample run:

4/7

Number: 0.5714285714285714

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote