Question

In: Computer Science

Assignment 4, Fraction Comparable Instructions For this assignment, you will be updating the Fraction class from...

Assignment 4, Fraction Comparable

Instructions

For this assignment, you will be updating the Fraction class from Assignment 1. To get started, you can either make a copy of your Assignment 1 Fraction.java or download the Fraction.java template at the bottom of this assignment.

You will need to update Fraction so that it implements the Comparable interface. This will require adding an implements statement to the class declaration as well as the compareTo method. You will also add a simplify method which reduces a fraction to its lowest terms and, to help you with this, a static method gcd which finds the greatest common divisor of two integers.

The requirements of the methods to be added are as follows:

  • int compareTo(Object other): Return -1 if this fraction is smaller than the fraction other, return 0 if this fraction is equal to the fraction other, and return 1 if this fraction is greater than the fraction other. Hint: To compare the two fractions, it will help to first convert them to fractions with a common (equal) denominator.
  • static int gcd(int a, int b): return the greatest common divisor of a and b. To find the gcd of two numbers there are several possible algorithms. One of these was showcased in term 1 lesson 19 - More Loops.
  • void simplify(): reduce the fraction to its simplest possible form: e.g. the fraction 12/18 should be reduced to 2/3. The static method gcd provides a useful helper for this method.

When you have successfully written your simplify method, you should add calls to this method at the end of the Fraction(int n, int d) constructor and the add method. This will ensure that fractions are always stored in their simplest possible form.

To test your code, download the runner class student_fraction_runner.java (Links to an external site.) into the same folder that holds your Fraction.java. Execute the method student_fraction_runner.main, and verify that the output matches the sample run listed below. Remember to change the runner to test with other values to make sure your program fits all the requirements. We will use a similar but different runner to grade the program.

When you are ready, paste your entire Fraction.java class in the box below, click run to test the output, and click submit when you are satisfied with your results.

Note: once you have completely finished the assignment feel free to add more methods (e.g. multiply) or extend the functionality of your Fraction class to include, for example, negative fractions. Make sure you submit your assignment first before making any changes like this.

Sample Run

Fraction 1: 4/5
Fraction 2: 3/2
Fraction 3: 4/5

Compare fraction 1 to fraction 2: -1
Compare fraction 2 to fraction 1: 1

Compare fraction 1 to fraction 3: 0
Compare fraction 3 to fraction 1: 0

Compare fraction 2 to fraction 3: 1
Compare fraction 3 to fraction 2: -1

Milestones

As you work on this assignment, you can use the milestones below to inform your development process:

Milestone 1: Write the static gcd method and test this by calling it on pairs of integers from another class.

Milestone 2: Write the simplify method (you will probably find it useful to call the gcd method). Add calls to this method at the end of the constructor and the add method.

Milestone 3: Implement the Comparable interface and write the method compareTo. Download the runner file and ensure the results are as expected.

Solutions

Expert Solution

// Please find the required solution

class Fraction implements Comparable {

    // define attributes for n and d
    private int n;
    private int d;

    // constructor for Fraction with n, d
    public Fraction(int n, int d) {
        this.n = n;
        this.d = d;

        // invoke simplify from constructor
        simplify();
    }

    // define getters
    public int getN() {
        return n;
    }

    public int getD() {
        return d;
    }

    // to string representation of fraction
    @Override
    public String toString() {
        return n + "/" + d;
    }

    // compares 2 fraction
    @Override
    public int compareTo(Object o) {
        Fraction c = (Fraction) o;
        return Integer.compare(n * c.d, c.n * d);
    }

    // returns gcd of 2 numbers
    public static int gcd(int x, int y) {
        if (y != 0)
            return gcd(y, x % y);
        else
            return x;
    }

    // simplify fraction using the following method
    void simplify() {
        int gcd = gcd(n, d);
        n = n / gcd;
        d = d / gcd;
    }
}

// sample student runner class 
public class student_fraction_runner {

    public static void main(String str[]) {
        Fraction fraction1 = new Fraction(4, 5);
        System.out.println("Fraction 1: " + fraction1);

        Fraction fraction2 = new Fraction(3, 2);
        System.out.println("Fraction 2: " + fraction2);

        Fraction fraction3 = new Fraction(4, 5);
        System.out.println("Fraction 3: " + fraction3);

        System.out.println();

        System.out.println("Compare fraction 1 to fraction 2: " + fraction1.compareTo(fraction2));
        System.out.println("Compare fraction 2 to fraction 1: " + fraction2.compareTo(fraction1));
        System.out.println();

        System.out.println("Compare fraction 1 to fraction 3: " + fraction1.compareTo(fraction3));
        System.out.println("Compare fraction 3 to fraction 1: " + fraction3.compareTo(fraction1));
        System.out.println();

        System.out.println("Compare fraction 2 to fraction 3: " + fraction2.compareTo(fraction3));
        System.out.println("Compare fraction 3 to fraction 2: " + fraction3.compareTo(fraction2));
        System.out.println();

        Fraction fraction4 = new Fraction(12, 18);
        System.out.println("Fraction 4: " + fraction4);

    }
}
sample screenshot:


Related Solutions

Homework Assignment 4 Instructions: Class name must be: HW4_yourName For example: Michael will name the class...
Homework Assignment 4 Instructions: Class name must be: HW4_yourName For example: Michael will name the class of homework assignment 4 as HW4_Michael Grading Rubric: Code running and as per the required conditions and giving expected output = 10 points File named as per instructions = 1 point Comments in code = 4 points Problem: Average calculation for a list Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for...
c++ Programming For this assignment you will be building on your Fraction class. However, the changes...
c++ Programming For this assignment you will be building on your Fraction class. However, the changes will be significant, so I would recommend starting from scratch and using your previous version as a resource when appropriate. You'll continue working on your Fraction class for one more week, next week. For this week you are not required to provide documentation and not required to simplify Fractions. Please keep all of your code in one file for this week. We will separate...
4) Define an abstract class Name Java class that implements interface Comparable   
4) Define an abstract class Name Java class that implements interface Comparable   
Create java class with name MyClass1 Instructions for MyClass1 For this portion of the assignment you...
Create java class with name MyClass1 Instructions for MyClass1 For this portion of the assignment you will need to create a java class of your own to model some objects in the real world or your own imagination. your classes should have at least three instances variables, accessor and mutator methods for each of those instance variables, one constructor method of any type, as well as an overridden toString method that will display every field value as part of a...
Assignment Instructions Module 4 Writing Assignment (M1-4) You will soon find yourself fulfilling roles in organizations...
Assignment Instructions Module 4 Writing Assignment (M1-4) You will soon find yourself fulfilling roles in organizations where the ability to think ethically about issues will make you much more valuable to employers. In this activity you will refer to the materials in your text and lectures to respond to the questions. Part A The questions in Part A refer to the material discussed in Module 1 of this course. Respond to the following. Discuss reasons why ethics are an important...
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...
Write a program to have a Car class which is comparable. Make the Car class comparable...
Write a program to have a Car class which is comparable. Make the Car class comparable and use speed to compare cars. Write a method in Main class that finds the minimum of 4 things (generically). Create 4 cars and pass the cars to the minimum method and find the smallest car. Have a toString method for the Car class. The main program should be able to find out how many cars are created so far by calling a static...
Review the General Programming Assignment instructions. In this chapter, the class dateType was designed to implement...
Review the General Programming Assignment instructions. In this chapter, the class dateType was designed to implement the date in a program, but the member function setDate and the constructor do not check whether the date is valid before storing the date in the member variables. Rewrite the definitions of the function setDate and the constructor so that the values for the month, day, and year are checked before storing the date into the member variables. Add a member function, isLeapYear,...
Please follow these instructions to complete this assignment: 1. For this assignment, you are to develop...
Please follow these instructions to complete this assignment: 1. For this assignment, you are to develop 10 questions that you would ask a management official responsible for the financial planning for the organization you have chosen to research for the week 3 paper. 2. Make sure the questions will give you insight into what the company looks for when preparing their yearly budget, fiscal planning strategies, as well as how they monitor their financial condition throughout the year and make...
Declare and define a class for a fraction number. A fraction in mathematics is defined as...
Declare and define a class for a fraction number. A fraction in mathematics is defined as a/b, where a and b are integers and called numerator and denominator. Requirements Task1    Define a fraction class that has the following member functions: constructor that initializes the fraction by default arguments. set function that sets the numerator of the fraction. set function that sets the denominator of the fraction. get function that returns the numerator of the fraction. get function that returns...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT