Question

In: Computer Science

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 a main method to even do ad hoc “testing” of your Fraction class.

The .java template can be found here: https://gofile.io/d/iW4eGp

Steps to Follow for this question
1. Read through this entire document without opening Eclipse
2. In Eclipse, create a new project called HW7_CIT591, then create a package in the src folder called “fraction”. Create a new class in the “fraction” package named Fraction.java, and fill it with empty stubs of the methods you will write later. See the Writing Method Stubs instructions on page 5.
3. Import the provided SampleFractionTest.java into your Java project and run the tests -- all tests should fail (for now)!
4. Implement enough code in the methods in Fraction.java to pass all tests.
5. Use pen and paper (or an electronic document) to generate a list of additional test cases you will use for each method in the Fraction class. You should have a total of at least 4 distinct and valid test scenarios (with individual test cases) per method (including the ones provided).
6. Create a second testing class file named FractionTest.java and write all of the additional test cases you generated in step 5. See the Writing Unit Tests instructions on page 7.
7. Update your implementation in the methods in Fraction.java to pass all additional tests.
a. If something fails:
i. Make sure all test cases are valid
ii. Fix any mistakes in your implementation

iii. Re-run the test file
iv. Repeat these steps until all tests pass
8. Re-run both test files to make sure all tests pass

A fraction is a number of the form numerator/denominator where the numerator and denominator are integers. The denominator cannot be 0. You may assume that no user will input a denominator of 0. The Fraction class needs to have two instance variables: numerator and denominator. The methods in this class are below. They have been provided with their method signatures.
public Fraction(int numerator, int denominator)
● The constructor to create a Fraction with the given numerator and denominator.
● The constructor should set the numerator and denominator instance variables in the Fraction class.
● The constructor should also properly format negative fractions. The convention is that negative fractions have the negative in the numerator.
● For example:
o Creating a new Fraction(4, 16) would set the numerator to 4 and the denominator to 16
o Creating a new Fraction(4, -16) would set the numerator to -4 and the denominator to 16
o Creating a new Fraction(-1, -2) would set the numerator to 1 and the denominator to 2
public void reduceToLowestForm()
● Reduce the current fraction by eliminating common factors.
● That is, turn a fraction like 4/16 into 1/4 and a fraction like 320/240 into 4/3.
● Remember, the convention is that negative fractions have the negative in the numerator.
● For example:
o A fraction like 4/16 would reduce to 1/4
o A fraction like 10/-15 would reduce to -2/3
o The reduced form of any fraction that represents 0 is 0/1
▪ e.g. 0/4 reduces to 0/1

public Fraction add(Fraction otherFraction)

Add the current fraction to the given otherFraction.
● Returns a new Fraction that is the sum of the two Fractions.
● The returned Fraction must be in reduced/lowest form.
● For example:
o Adding the fraction 3/5 to the fraction 1/4 reduces to 17/20
o Adding the fraction -1/2 to the fraction 2/-3 reduces to -7/6

public Fraction subtract(Fraction otherFraction)
● Subtract the given otherFraction from the current fraction.
● That is, thisFraction - otherFraction.
● Returns a new Fraction that is the difference of the two Fractions.
● The returned Fraction must be in reduced/lowest form.
● For example:
o Subtracting the fraction 3/9 from the fraction 5/9 reduces to 2/9
o Subtracting the fraction 5/16 from the fraction 4/16 reduces to -1/16
public Fraction mul(Fraction otherFraction)
● Multiply the current fraction by the given otherFraction.
● Returns a new Fraction that is the product of this fraction and the otherFraction.
● The returned Fraction must be in reduced/lowest form.
● For example:
o Multiplying the fraction 1/2 by the fraction 2/3 reduces to 1/3
public Fraction div(Fraction otherFraction)
● Divide the current fraction by the given otherFraction.
● That is, thisFraction / otherFraction.
● Returns a new Fraction that is the quotient of this fraction and the otherFraction.
● The returned Fraction must be in reduced/lowest form.
● For example:
o Dividing the fraction 4/16 by the fraction 5/16 reduces to 4/5
public double decimal()
● Return this fraction in decimal form.
● For example:
o For the fraction 2/4, this method should return the value 0.5
o For the fraction 1/3, this method should return the approximate value 0.3333333333333333
▪ Note, to unit test double values like this, use assertEquals with a delta (see the lecture slides on Comparing Floating Point Types)

public void sqr()

● Square the current fraction.
● This method modifies the current fraction and reduces it to lowest form.
● For example:
o A fraction like 2/3 will become 4/9
o A fraction like 4/16 will become 1/16
public Fraction average(Fraction otherFraction)
● Average the current fraction with the given otherFraction.
● Return a new Fraction that is the average of this fraction and the otherFraction.
● The returned Fraction must be in reduced/lowest form.
● For example:
o Averaging the fraction 5/8 with the fraction -12/16 reduces to -1/16
public static Fraction average(Fraction[] fractions)
● Static method to average all of the fractions in the given array.
o Note, you don’t need to create an instance of the Fraction class in order to call a static method
o For example, you should be able to call this method with the class name (note upper-case in “Fraction”)
Fraction f = Fraction.average(myArrayOfFractions);
● Do not include the current fraction in the average.
● Return the average of the array.
● The returned Fraction must be in reduced/lowest form.
● If the array is empty, return a new Fraction that equals 0. That is 0/1.
● For example:
o The average of the fractions 3/4, 3/5, and 3/6 reduces to 37/60
public static Fraction average(int[] ints)
● Static method to average all the integers in the given array.
o Again, you don’t need to create an instance of the Fraction class in order to call a static method
o For example, you should be able to call this method with the class name (note upper-case in “Fraction”)
Fraction f = Fraction.average(myArrayOfInts);
● Do not include the current fraction in the average.
● Return the average of the array as a new Fraction.

● The returned Fraction must be in reduced/lowest form.
● If the array is empty, return a new Fraction that equals 0. That is 0/1.
● For example:
o The average of the ints 1, 2, 3, and 4 reduces to 5/2
@Override
public boolean equals(Object object)
● Overriden method to compare the given object (as a fraction) to the current fraction, for equality. (See the lecture slides on Testing for Equality)
● Two fractions are considered equal if they have the same numerator and same denominator, after eliminating common factors.
● This method does not (permanently) reduce the current fraction to lowest form.
● For example:
o The fraction 2/3 is equal to the fraction 2/3
o The fraction 4/16 is equal to the fraction 1/4, but the fraction 4/16 is not reduced to lowest form.

@Override
public String toString()

● Overriden method to return a string representation of the current fraction.
● A fraction like 2/3 will be represented in string form as “2/3”.
● There is a no whitespace in this string.
● If the fraction is negative, it will be expressed as “-2/3”, not “2/-3”.
Tip: You are always encouraged to write additional helper methods! We highly recommend that if you write helper methods, you test them.

Please submit all your Java classes to Codio. Make sure it is all put in the “src” folder. Included should be 3 files: your Fraction.java, your FractionTest.java, and our SampleFractionTest.java.

Solutions

Expert Solution


public class HelloWorld{

     public static void main(String []args){
        // System.out.println("Hello World");
        
        Fraction fract = new Fraction(-15,5);
        Fraction fract1 = new Fraction(10,4);
        int[] ints = {0,6,4,3,6,7};
        System.out.println(Fraction.average(ints));
        
       
     }
     
     
}
class Fraction
{
    int numerator;
    int denominator;
    
    public Fraction(int numerator, int denominator)
    
    {
    
    this.numerator = numerator;
    this.denominator = denominator;
    }
    
    public void setNumerator()
    {
        if(this.denominator < 0)
        {
            this.numerator = this.numerator * -1;
        }
        
    }
    
    public int getNumerator()
    {
        return this.numerator;
    }
    
    
    
    public void setDenominator()
    {
        if(this.denominator < 0)
        {
            this.denominator = this.denominator * -1;
        }
        
    }
    
    public int getDenominator()
    {
        return this.denominator;
    }
    
    public int calculateHCF(int numerator, int denominator) 
    {
        if (numerator % denominator == 0) 
        {
                 return denominator;
        }
            return calculateHCF(denominator, numerator % denominator);
        }
    
    
    void reduceToLowestForm() 
    {
        int hcf = calculateHCF(numerator, denominator);
        numerator = numerator/hcf;
        denominator = denominator/hcf;
        
    }
    
    public Fraction add(Fraction otherFraction) 
    {
        int num = (numerator * otherFraction.getDenominator()) + 
                                (otherFraction.getNumerator() * denominator);
        int den = denominator * otherFraction.getDenominator();
        
        int hcf = calculateHCF(numerator, denominator);
        numerator = numerator/hcf;
        denominator = denominator/hcf;
        return new Fraction(num, den);
    }
    
    public Fraction subtract(Fraction otherFraction)
    {
        int newNum = (numerator * otherFraction.denominator) - 
                                 (otherFraction.numerator * denominator);
            int newDen = denominator * otherFraction.denominator;
            
            
            Fraction result = new Fraction(newNum, newDen);
            
            int hcf = calculateHCF(newNum, newDen);
        newNum = newNum/hcf;
        newDen = newDen/hcf;
            return result;
    }
    
    public Fraction mul(Fraction otherFraction)
    {
        int newNum = numerator * otherFraction.numerator;
        int newDen = denominator * otherFraction.denominator;
        Fraction result = new Fraction(newNum, newDen);
        return result;
    }
    
    
    public Fraction div(Fraction otherFraction)
    {
        int newNum = numerator * otherFraction.getDenominator();
        int newDen = denominator * otherFraction.numerator;
        Fraction result = new Fraction(newNum, newDen);
        return result;
    }
    
    public double decimal()
    {
        double dec = numerator / denominator;
        return dec;
    }
    
    public void sqr()
    
    {
           int newNum = numerator * numerator;
           int newDen = denominator * denominator;
    }
       
    public Fraction average(Fraction otherFraction)
    {
        int num = (numerator * otherFraction.getDenominator()) + 
                                (otherFraction.getNumerator() * denominator);
        int den = denominator * otherFraction.getDenominator();
        
        return new Fraction(num, den*2);
    }
    
    
    @Override
    public String toString() 
    {
            return this.numerator + "/" + this.denominator;
    }
    
    
    
    @Override
    public boolean equals(Object object)
    {
        Fraction f = new Fraction(3,5);
        int hcf1 = calculateHCF(f.getNumerator(), f.getDenominator());
        double fractionFloatValue = (f.getNumerator()/hcf1) / (f.getDenominator()/hcf1); 
        int hcf2 = calculateHCF(this.getNumerator(), this.getDenominator());
        double fractionFloatValue2 = (this.getNumerator()/hcf2) / (this.getDenominator()/hcf2);
        return (fractionFloatValue == fractionFloatValue2) ? true : false;
    }
    
    public static Fraction average(int[] ints)
    {
        
        int len = ints.length;
        int sum = 0;
        for(int i = 0; i<len; i++)
        {
            sum += ints[i];
        }
        
        Fraction result1 = new Fraction(sum, len);
        int hcf = result1.calculateHCF(sum, len);
        sum = sum/hcf;
        len = len/hcf;
        Fraction result = new Fraction(sum, len);
        
        
        
        
    //  sum = sum/hcf;
    //  len = len/hcf;
        
        return result;
    }
    
      
    
    
}

Hi, I hope this helps. Sorry, one method is not there in this code. public static Fraction average(Fraction[] fractions), this method. This method is also like the other static method. I am sure by going through that method you will be able to understand how to do this method. Still, if there is any prob, please let me know.


Related Solutions

Create a c++ class called Fraction in which the objects will represent fractions. Remember:   do not...
Create a c++ class called Fraction in which the objects will represent fractions. Remember:   do not reduce fractions, do not use "const," do not provide any constructors, do not use three separate files. You will not receive credit for the assignment if you do any of these things. In your single file, the class declaration will come first, followed by the definitions of the class member functions, followed by the client program. It is required that you provide these member...
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...
Java program. Need to create a class names gradesgraph which will represent the GradesGraphtest program. Assignment...
Java program. Need to create a class names gradesgraph which will represent the GradesGraphtest program. Assignment Create a class GradesGraph that represents a grade distribution for a given course. Write methods to perform the following tasks: • Set the number of each of the letter grades A, B, C, D, and F. • Read the number of each of the letter grades A, B, C, D, and F. • Return the total number of grades. • Return the percentage of...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
Java Coding Background You will create a Java class that simulates a water holding tank. The...
Java Coding Background You will create a Java class that simulates a water holding tank. The holding tank can hold volumes of water (measured in gallons) that range from 0 (empty) up to a maximum. If more than the maximum capacity is added to the holding tank, an overflow valve causes the excess to be dumped into the sewer system. Assignment The class will be named HoldingTank. The class attributes will consist of two int fields – current and maxCapacity....
In java: -Create a class named Animal
In java: -Create a class named Animal
In Java, create an abstract vehicle class. Create a Truck Class that Inherits from Vehicle Class....
In Java, create an abstract vehicle class. Create a Truck Class that Inherits from Vehicle Class. The vehicle class should contain at least 2 variables that could pertain to ANY vehicle and two methods. The truck class should contain 2 variables that only apply to trucks and one method. Create a console program that will instantiate a truck with provided member information then call one method from the truck and one method contained from the inherited vehicle class. Have these...
C++ Create a class for working with fractions. Only 2 private data members are needed: the...
C++ Create a class for working with fractions. Only 2 private data members are needed: the int numerator of the fraction, and the positive int denominator of the fraction. For example, the fraction 3/7 will have the two private data member values of 3 and 7. The following methods should be in your class: a. A default constructor that should use default arguments in case no initializers are included in the main. The fraction needs to be stored in reduced...
java For this assignment, you will create a Time class that holds an hour value and...
java For this assignment, you will create a Time class that holds an hour value and a minute value to represent a time. We will be using "military time", so 12:01 AM is 0001 and 1 PM is 1300. For this assignment, you may assume valid military times range from 0000 to 2359. Valid standard times range from 12:00 AM to 11:59 PM. In previous assignments, we had a requirement that your class be named Main. In this assignment, the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT