Description: So far, in working with numbers we have worked with ints and double
ID: 3681646 • Letter: D
Question
Description:
So far, in working with numbers we have worked with ints and doubles, where we have learned that doubles are inherently inexact. Since we know a rational number can be represented as a pair of integers, our goal is to create an object Rational that we can treat with the same 'trust' as int but allows us more precision.
Objective:
1. Download the abstract class Num (https://cse.sc.edu/~pade/csce145/assign/HW08/Num.java)
2. Write a class Int that extends Num. This class should have a single instance variable. It should also override definitions for the following methods:
----getApproxVal
----compare
----toString
In addition, you should have a constructor and a method getVal that returns the exact value of the Int as a Java primitive (int).
3. Write a java class Rational that has two instance variables:
----Int numer : The numerator
----Int denom : The denominator
This class should override definitions for the same 3 methods as above. In addition it should have a constructor that takes two ints as well as the following methods (to replace getVal in Int):
----getNumer
----getDenom
4. Finally, write a class InvalidDenomException that extends RuntimeException. Modify the constructor in Rational to throw an InvalidDenomException if anyone tries to set the denominator to zero.
You do not need a main method for this assignment. If you wish to test your code, you may use the test class provided here: TestNumbers (https://cse.sc.edu/~pade/csce145/assign/HW08/TestNumbers.java)
As a final note, make sure that in all your compare methods you compare by the actual values of the numbers, not by the values returned by getApproxVal.
Example:
This is example output given the provided test program
Finally:
Submit Int.java, Rational.java, and InvalidDenomException.java to the dropbox
Remember that your source code MUST have appropriate headers and MUST contain appropriate comments.
Explanation / Answer
CODE
Rational:
package sophy;
public class Rational {
Int numer;
Int denom;
public Rational(int numer,int denom) throws InvalidDenomException {
int rat=numer/denom;
}
public Int getNumer() {
return numer;
}
public void setNumer(Int numer) {
this.numer = numer;
}
public Int getDenom() {
return denom;
}
public void setDenom(Int denom) {
this.denom = denom;
}
}
CODE:Int.java
public class Int implements Num{
@Override
public int compare(Num that) {
return 0;
}
@Override
public double getApproxVal() {
return 0;
}
@Override
public boolean lessThan(Num that) {
return false;
}
}