Creating the toString method

By default, all classes in Java have a toString method. The toString method is simply a method that returns the String representation or state of an object. The default functionality of toString is usually not desirable as it returns the memory address of an object in String format (this will be made more clear later on in the semester). For now, we will create our own version of toString that more aptly represents a Fraction as a String.

Something like the following will be sufficient:

	Your fraction:
		numerator = 2
		denominator = 7

To achieve this, we will form a String by concatenating Fraction's numerator and denominator values.

/**
 * Returns a String representation of this Fraction.
 * @return A String representation of this Fraction
 */
public String toString()
{
	String returnString = "Your fraction:\n";
	returnString += "\tnumerator = " + getNumerator() + "\n";
	returnString += "\tdenominator = " + getDenominator();
	return(returnString);
}

Testing

Since we now have a constructor and a toString method, we may run the first part of our test program. Two Fractions will be constructed via user input and the toString method will be invoked to output the Fractions to the console.

Un-comment the code in main that performs these steps:

  1. Create a Scanner object on System.in
  2. Use the Scanner object to get the numerator of the first fraction
  3. Use the Scanner object to get the denominator of the first fraction
  4. Create the first fraction object with input provided in the last 2 steps
  5. Use the Scanner object to get the numerator of the second fraction
  6. Use the Scanner object to get the denominator of the second fraction
  7. Create the first fraction object with input provided in the last 2 steps
  8. Print out the two fractions by invoking the toString method on both the objects

Run your code to make sure everything you have implemented so far works. It is easier to find errors if you write and then test a little bit at a time, rather than writing an entire project at once and then attempting to debug the entire thing.