Create a class Rational that represents a rational number. It should have privat
ID: 3626024 • Letter: C
Question
Create a class Rational that represents a rational number. It should have private attributes for* The numerator (an integer)
* The denominator (an integer)
and the following methods:
* Rational(numerator, denominator)?a constructor for a rational number.
* Accessor methods getNumerator and getDenominator and mutator methods setNumerator and setDenominator for the numerator and the denominator. You should use an exception to guarantee that the denominator is never zero.
The Java project requires three classes:
1. Rationale
2. Driver
3. an exception class that you write by inheriting from Java's Exception class.
Be sure to use a try/catch statement in the Rationale class
Explanation / Answer
class Rational
{
private int numerator;
private int denominator;
public int getDenominator() {
return denominator;
}
public int getNumerator() {
return numerator;
}
public void setDenominator(int denominator) throws zeroException {
if(denominator == 0)
throw new zeroException("Denominator cant be zero");
else
this.denominator = denominator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
}
class zeroException extends Exception {
public zeroException() {
}
public zeroException(String msg) {
super(msg);
}
}
public class Driver {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws zeroException {
Rational R = new Rational();
R.setNumerator(5);
R.setDenominator(0);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.