Question

In: Computer Science

Java Program to write a Fraction class that models a mathematical fraction. The fraction class needs...

Java Program to write a Fraction class that models a mathematical fraction. The fraction class needs to support simple arithmetic functions including taking the sum, difference, and the product of the division of the two.

Do not include a main() method in the Fraction class.

The Fraction class will implement the following class methods:

Fraction add (Fraction f1, Fraction f2);        // f1 + f2 and returns a new Fraction
Fraction sub (Fraction f1, Fraction f2);        // f1 - f2 and returns a new Fraction
Fraction mul (Fraction f1, Fraction f2);        // f1 * f2 and returns a new Fraction
Fraction div (Fraction f1, Fraction f2);        // f1 / f2 and returns a new Fraction

It will also implement the following instance methods:

Fraction(int n, int d);         // constructor where *n* is numerator and *d* is the denominator
Fraction reduce();                      // Fraction is lowest common form
String strVal();                        // String representation, e.g., 3/4

if the denominator is 0, treat it as 1 for now until we cover exceptions in more depth during this course. If you're already comfortable with exceptions, then ignore the previous statement and throw an exception in the constructor if the given denominator is 0.

Note that you do not need to deal with mixed numbers. In other words, you can deal with fractions as fractions and do not need to deal with whole numbers plus fractional parts. Also, the Fraction class should work fine when the fraction is improper, i.e., when the numerator is >= the denominator.

The following is sample code from a set of unit tests or client program that uses the Fraction class.

// Client code
Fraction f1 = new Fraction(1, 2);               
Fraction f2 = new Fraction(3, 2);               
Fraction sum = Fraction.add(f1, f2);    
Fraction whole = sum.reduce();                  
System.out.println(whole.strVal());             

// More examples
Fraction f3 = new Fraction(3, 4);               
Fraction f4 = new Fraction(1, 3);               
Fraction f5 = Fraction.sub(f3, f4);             
System.out.println(f5.strVal());                

In order to reduce a fraction, you will need to find the Greatest Common Divisor (GCD) between the numerator and the denominator. To do this, you can use Euclid's algorithm. If you are already comfortable with recursion, you can use a recursive version. If not (we cover recursion later in this course), you can use the following to compute the GCD.

private int gcd(int num1, int num2)
{
        int tmp;
        num1 = abs(num1);
        num2 = abs(num2);
        while (num1 > 0) {
                tmp = num1;
                num1 = num2 % num1;
                num2 = tmp;
        }
        return num2;
}

Once you've computed the GCD, finding the reduced fraction is simple. Do an Internet search to figure it out.

Additionally, in order to add and subtract Fractions, you'll need to calculate the Least Common Denominator (LCD). Part of "doing software" is to find examples and information on the Internet. In order to calculate the LCD, you will need the Least Common Multiple (LCM) and the Greatest Common Divisor (GDC).

Solutions

Expert Solution

file-name:    Fraction.java
------------------------------------------------
import static java.lang.Math.abs;
/*
Fraction class
* It has two member variables 
1. numerator
2.denominator

*I have created gcd and LCM methods which help us in calculation fractions.
 */
public class Fraction {

    // instance variables
    int numerator;
    int denominator;

    // constructor
    Fraction( int n , int d) {
        this.numerator = n;
        if( d == 0) {
            d = 1;
        }
        this.denominator = d;
    }

    // add method
    public static Fraction add(Fraction f1, Fraction f2) {
        int den = LCMofDen(f1,f2);

        int den1 = f1.denominator;
        int den2 = f2.denominator;

        int num1 = f1.numerator;
        int num2 = f2.numerator;

        int num = num1*(den/den1) + num2*(den/den2);

        Fraction temp = new Fraction(num,den);
        temp = temp.reduce();
        return temp;
    }// add method ended

    // sub method ( performs subtraction of fractions )
    public static Fraction sub(Fraction f1, Fraction f2) {
        int den = LCMofDen(f1,f2);

        int den1 = f1.denominator;
        int den2 = f2.denominator;

        int num1 = f1.numerator;
        int num2 = f2.numerator;
        int num = num1*(den/den1) - num2*(den/den2);
        Fraction temp = new Fraction(num,den);
        temp = temp.reduce();
        return temp;

    } // sub method ended

    // mul method:
    // performs multiplication of fractions
    public Fraction mul(Fraction f1, Fraction f2) {
        int den1 = f1.denominator;
        int den2 = f2.denominator;

        int num1 = f1.numerator;
        int num2 = f2.numerator;

        int num = num1*num2;
        int den = den1*den2;

        Fraction temp = new Fraction(num,den);
        temp = temp.reduce();
        return temp;
    } // mul method ended

    // div method:
    public Fraction div(Fraction f1, Fraction f2) {
        int den1 = f1.denominator;
        int den2 = f2.denominator;

        int num1 = f1.numerator;
        int num2 = f2.numerator;

        int num = num1*den2;
        int den = den1*num2;
        Fraction temp = new Fraction(num,den);
        temp = temp.reduce();
        return temp;
    } // div method ended

    /*
    This method LCMofDen 
    it calculates , LCM of denominators ( only useful with addition and subtraction of fractions )
     */
    private static int LCMofDen( Fraction f1, Fraction f2 ) {

        int den1 = f1.denominator;
        int den2 = f2.denominator;

        int resGCD = gcd(den1,den2);
        int den = (den1*den2)/resGCD;

        return den;
    } // end of LCM method

    /*
    This method reduces the fraction into simple form
    * we use gcd of numerator and denominator.
    * GCD of numerator and denominator gives us the highest common divisor
    * and we divide numerator and denominator with that divisor 
    * so, we convert them into simplest form.
     */
    public Fraction reduce() {
        int num1 = this.numerator;
        int num2 = this.denominator;
        int hcf =  gcd(num1, num2);

        this.numerator = num1/hcf;
        this.denominator = num2/hcf;

        return new Fraction(this.numerator , this.denominator);
    } // reduce method ended

    /*
    calculates the gcd of two numbers 
     */
    private static int gcd(int num1, int num2)
    {
        int tmp;
        num1 = abs(num1);
        num2 = abs(num2);
        while (num1 > 0) {
            tmp = num1;
            num1 = num2 % num1;
            num2 = tmp;
        }
        return num2;
    } // end of gcd method

    // to print the fractions in understandable way
    public String strVal() {
        return this.numerator +"/"+this.denominator ;
    }

} // END of Fraction class

--------------------------------------------------------------------------------------------------------------------------------------

file-name:     Main.java
-----------------------------------
/*
This Main method acts as a Tester class to test Fraction class.
I did not use any Scanner methods, I just took example input as given in question.
If you want I can add code that takes user input and calculate.
 */
public class Main {
    public static void main(String[] args) {

        Fraction f1 = new Fraction(1,2);
        Fraction f2 = new Fraction(3,2);
        Fraction sum = Fraction.add(f1,f2);
        Fraction whole = sum.reduce();
        System.out.println(whole.strVal());

        Fraction f3 = new Fraction(3,4);
        Fraction f4 = new Fraction(1,3);
        Fraction f5 = Fraction.sub(f3,f4);
        System.out.println(f5.strVal());
    } // main( ) method ended
} // Main class ended

--------------------------------------------------------------------------------------------

OUTPUT :

THANK YOU !! , If you like my effort please upvote. Let me know if you have any doubts in comment section


Related Solutions

Needs to be in JAVA. Write a Java program that accepts the total amount of cars...
Needs to be in JAVA. Write a Java program that accepts the total amount of cars sold and total sales amount of a car salesperson for a given month. The salesperson’s paycheck is computed as follows: a. Every sales person gets 10% (commission) of total sales b. Sales totals greater than $50,000 get 5% of total sales amount c. 8 or more cars sold earns the salesperson an extra 3% Please remove 30% (taxes) of the gross pay and list...
Write these java classes: 1) DynArray.java: a class that models some of the functionality of the...
Write these java classes: 1) DynArray.java: a class that models some of the functionality of the Java ArrayList. This class is not complete and must be modified as such: Write the method body for the default constructor Write the method body for the methods: arraySize(), elements(), grow(), shrink(). The incomplete code is provided here: public class DynArray { private double[] array; private int size; private int nextIndex;    public int arraySize() { }    public int elements() { } public...
Write a java program that has a class named Octagon that extends the class Circ and...
Write a java program that has a class named Octagon that extends the class Circ and implements Comparable (compare the object's area) and Cloneable interfaces. Assume that all the 8 sides of the octagon are of equal size. Your class Octagon, therefore, must represent an octagon inscribed into a circle of a given radius (inherited from Circle) and not introduce any new class variables. Provide constructors for clas Octagon with no parameters and with 1 parameter radius. Create a method...
Java Write a program to record the GPAs of a class and find the percentage of...
Java Write a program to record the GPAs of a class and find the percentage of students in each GPA. The program first allows the user to enter the number of students enrolled in the class, and then to enter the GPA of all students one by one. For each student, the input must be between 1 and 4 inclusively. Otherwise, the software displays a message as “Invalid number!” and asks for a new GPA for the same student Enter...
JAVA FRACTIONS QUESTION: You will create a Fraction class in Java to represent fractions and to...
JAVA FRACTIONS QUESTION: You will create a Fraction class in Java to represent fractions and to do fraction arithmetic. To get you used to the idea of unit testing, this homework does not require a main method. You can create one if you find it useful, however, we will not be grading or even looking at that code. You should be comfortable enough with the accuracy of your test cases that you do not need to use print statements or...
Write a Java program such that it consists of 2 classes: 1. a class that serves...
Write a Java program such that it consists of 2 classes: 1. a class that serves as the driver (contains main()) 2. a class that contains multiple private methods that compute and display a. area of a triangle (need base and height) b area of a circle (use named constant for PI) (need radius) c. area of rectangle (width and length) d. area of a square (side) e. surface area of a solid cylinder (height and radius of base) N.B....
Write a program in java that does the following: Create a StudentRecord class that keeps the...
Write a program in java that does the following: Create a StudentRecord class that keeps the following information for a student: first name (String), last name (String), and balance (integer). Provide proper constructor, setter and getter methods. Read the student information (one student per line) from the input file “csc272input.txt”. The information in the file is listed below. You can use it to generate the input file yourself, or use the original input file that is available alone with this...
Write a Java program such that it consists of 2 classes: 1. a class that serves...
Write a Java program such that it consists of 2 classes: 1. a class that serves as the driver (contains main()) 2. a class that contains multiple private methods that compute and display a. area of a triangle (need base and height) b area of a circle (use named constant for PI) (need radius) c. area of rectangle (width and length) d. area of a square (side) e. surface area of a solid cylinder (height and radius of base) N.B....
Needs to be in basic JAVA Write a program that does basic encrypting of text. You...
Needs to be in basic JAVA Write a program that does basic encrypting of text. You will ask the user the filename of a text file that contains a few sentences of text. You will read this text file one character at a time, and change each letter to another one and write out to an output file. The conversion should be done a -> b, b->c , … z->a, A->B, B->C, …. Z->A. This means just shift each letter...
write the program in java. Demonstrate that you understand how to use create a class and...
write the program in java. Demonstrate that you understand how to use create a class and test it using JUnit Let’s create a new Project HoursWorked Under your src folder, create package edu.cincinnatistate.pay Now, create a new class HoursWorked in package edu.cincinnatistate.pay This class needs to do the following: Have a constructor that receives intHours which will be stored in totalHrs Have a method addHours to add hours to totalHrs Have a method subHours to subtract hours from totalHrs Have...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT