Question
Develop a Fraction class that is capable of doing arithmetic with fractions. An outline of the class is given below. Fractions are held in lowest
- Develop a Fraction class that is capable of doing arithmetic with fractions. An outline of the class is given below. Fractions are held in lowest terms, that is, you should divide out any common multiple of the numerator and denominator. The gcd() method will help with this. You should complete the implementations of all the class methods (including the constructors). Also create a TestFraction class and paste in the code shown below. Your Fraction class should produce the correct results when used in TestFraction.
public class Fraction {
int numerator;
int denominator;
Fraction() { // numerator = denominator = 1
// add code here
}
Fraction(int n, int d) {
// add code here
}
// greatest common divisor:
int gcd(int a, int b) {
if (b == 0)
return (a);
else
return (gcd(b, a % b));
}
public String toString() {
// add code here
}
String toDecimal() {
// add code here
}
Fraction add(Fraction f) {
// add code here
}
}
public class TestFraction {
public static void main(String[] args) {
Fraction f1 = new Fraction();
Fraction f2 = new Fraction(1, 3);
Fraction f3 = new Fraction(3, 6);
System.out.println("f1 = " + f1);
System.out.println("f2 = " + f2);
System.out.println("f3 = " + f3);
System.out.println("f1 + f2 = " + f1.add(f2));
System.out.println("f2 in decimal is: " + f2.toDecimal());
}
}
With my classes, this prints
f1 = 1/1
f2 = 1/3
f3 = 1/2
f1 + f2 = 4/3
f2 in decimal is: 0.33333334
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started