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

  1. 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!