Colorado State University

Recitation R13 - The Fraction Class
Spring 2016

CS160: Foundations in Programming


Setting up the Class

  1. Declare two instance variables of type int called numerator and denominator.
  2. Create a private static method called gcd.

Testing Phase One

Because the gcd method will be used in one of our constructors, let's make sure that it's working properly. Call the gcd method in your main with the following inputs:

Creating the Constructors and the toString methods

  1. The first constructor should take two integers. These integers should be simplified using the gcd method before assigning them to the instance variables. After simplifying, assign the first integer to the numerator and the second integer to the denominator.
  2. The second constructor should take one integer. Inside the constructor you can make a call to your first constructor by using the following code: this(myInt, 1); myInt represents the parameter. This will call the first contructor you made and assign a fraction using those arguments.
  3. Create two accessor methods called getNumerator and getDenominator. These methods should have no parameters and return ints. These methods should return the values of the instance variables.
  4. We need a way to represent the fractions. Create a toString method that returns the following String without a newline: numerator / denominator

Testing Phase Two

After the code you wrote to test the gcd method, create and print three Fractions: Print all three fractions out and make sure your output matches the following:
// Fraction one
7 / 1
// Fraction two
3 / 4
// Fraction  three
5 / 6

The Methods

In this next part you will create methods that add, subtract, multiply, and divide fractions.
  1. Create a public method called add.
  2. Create a public method called subtract. This method very similar to your last method, however, instead of adding the numerators you will want to subtract them.
  3. Create a public method called multiply. This method should return a new Fraction that is the product of the numerators and the denominators.
  4. Create a public method called divide. This method should return a new Fraction where the numerator is the product of the numerator from the first Fraction with the denominator from the second Fraction and the denominator is the product of the denominator from the first Fraction and the numerator from the second Fraction.

Testing Phase Three

From phase two, the second Fraction should be 3/4 and the second Fraction should be 5/6. Test your methods out by adding, subtracting, multiplying, and dividing these Fractions together. Your output should be:
// Adding
19 / 12
// Subtracting
-1 / 12
// Multiplying
5 / 8
// Dividing
9 / 10 

© 2016 CS160 Colorado State University. All Rights Reserved.