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
public String toString() { String returnString = "Your fraction:\n"; returnString += "\tnumerator = " + getNumerator() + "\n"; returnString += "\tdenominator = " + getDenominator(); return(returnString); }
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:
Scanner scanner = new Scanner(System.in); int numerator = 1; int denominator = 1; System.out.println("Enter the numerator of the first fraction "); numerator = scanner.nextInt(); System.out.println("Enter the denominator of the first fraction "); denominator = scanner.nextInt(); Fraction firstFraction = new Fraction(numerator, denominator); System.out.println("Enter the numerator of the second fraction "); numerator = scanner.nextInt(); System.out.println("Enter the denominator of the second fraction "); denominator = scanner.nextInt(); Fraction secondFraction = new Fraction(numerator, denominator); System.out.println("The first fraction is " + firstFraction.toString()); System.out.println("The Second Fraction is " + secondFraction.toString()); /* System.out.printf("The decimal value of the first fraction is %.2f\n", firstFraction.decimalValue()); System.out.printf("The decimal value of the second fraction is %.2f\n" , secondFraction.decimalValue()); Fraction reciprocalFirstFraction = firstFraction.reciprocal(); System.out.println("The reciprocal of first fraction is " + reciprocalFirstFraction.toString()); Fraction reciprocalSecondFraction = secondFraction.reciprocal(); System.out.println("The reciprocal of the second fraction is " + reciprocalSecondFraction.toString()); System.out.println("The product of the two fractions is " + firstFraction.multiply(secondFraction).toString()); System.out.println("Dividing first fraction by the second fraction leads to " + firstFraction.divideBy(secondFraction)); */