Write a Java class Rational that is intended to store a rati

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.

Solution

public class Rational

{

private int num = 0, den = 1;

public Rational(int num, int den)

{

if(den == 0) throw DenominatorZeroException( );

try{

this.num = num;

this.den = den;

}

catch(Exception e) {

e.printStackTrace( );

//System.exit(0);

}

}

public float getNumber( )

{

float result = null;

if(den == 0) throw DenominatorZeroException( );

try {

result = num / den ;

}

catch(Exception e) {

e.printStackTrace( );

}

return result;

}

public float sqrt( )

{

  if(den == 0) throw DenominatorZeroException( );

float result = null;

try{

result = Math.sqrt(num/den);

}

catch(Exception e){

e.printStackTrace( );

}

return result;

}

public static void main(String args[ ])

{

Rational r1 = new Rational( 1, 2 );

float r1Value = r1.getNumber( );

Rational r2 = new Rational( 4, 0 );

float r2Value = r2.getNumber( );

}

}

class DenominatorZeroException extends ArithmeticException

{

public DenominatorZeroException( ) { super(\"Attempted to assign denominator of Rational to Zero\"); }

public DenominatorZeroException(String message){ super(message); }

}

Write a Java class Rational that is intended to store a rational number represented in the form numerator / denominator, where numerator and denominator are int
Write a Java class Rational that is intended to store a rational number represented in the form numerator / denominator, where numerator and denominator are int

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site