Fractions

  1. Create a new class named Fraction that models fractions, such as 2/3 or 45/9. Implement the following API:
  2. Create a testing program, TestFraction, that prompts the user to provide the numerator and denominator of a fraction, creates the corresponding Fraction object, then prints both it and a simplified version.
    1. If the denominator is 1, it should be omitted when printed. (This test should take place in your toString method.)
  3. Provide a transcript of five executions of TestFraction, using different values for numerator and denominator that demonstrate that your program runs correctly.

Hint:

Here's a sample piece of testing code:

Fraction bob = new Fraction(2,4);
Fraction sue = bob.simplify();
System.out.println("bob is "+bob+" and sue is "+sue);

should result in the output

bob is 2/4 and sue is 1/2

For now, make sure the names of the parameters in your constructors differ from the names of the corresponding instance variable(s) that the constructor is initializing. Later we'll see a better way to handle this. Here's an example:

class Cat {
  public int height;
  public int weight;
  public Cat(int myWeight, int myHeight) {
    height = myHeight;
	weight = myWeight;
  }
}

Sample output:

Please enter a numerator and denominator (0 0 to stop): 3 14

You entered the fraction 3/14 which simplifies to 3/14.
Please enter a numerator and denominator (0 0 to stop): 12 42
You entered the fraction 12/42 which simplifies to 2/7
Please enter a numerator and denominator (0 0 to stop): 48 12
You entered the fraction 48/12 which simplifies to 4
Please enter a numerator and denominator (0 0 to stop): 68 48
You entered the fraction 68/48 which simplifies to 17/12
Please enter a numerator and denominator (0 0 to stop): 0 0

The tricky part about this problem is the simplify method. You'll need a loop. Start with the smaller--call it smaller--of the numerator and denominator. If both the numerator and denominator divide evenly by smaller, you're done--just divide both by smaller to get the simplified fraction. Else, keep shrinking smaller until you find a value that both are evenly divisible by, in which case, divide both numerator and denominator by this and set smaller to be the smaller of the numerator and denominator and continue with the loop. Continue looping until smaller obtains 1. Create a new Fraction with whatever result you have obtained and return it.