/* * Parke Godfrey * 2009-10-21 * Compute the difference between a list of fractions * and print the sum of the differences. */ import java.io.PrintStream; import java.util.Scanner; import type.lib.Fraction; public class FractionDiff { public static void main(String[] args) { PrintStream output = System.out; Scanner input = new Scanner(System.in); // Get the number of fractions to read in. output.println("Number of fractions to enter?"); int numOfFrac = input.nextInt(); // Read in the first fraction. output.println("Enter fraction #1 (numerator denominator):"); Fraction before = new Fraction(input.nextLong(), input.nextLong()); // Declare a fraction to accumulate the sum. // Should be "zero" to start. Fraction sum = new Fraction(); // Read in subsequent fractions, computing the differences. for (int i = 2; i <= numOfFrac; i++) { output.println("Enter fraction #" + i + " (numerator denominator):"); Fraction current = new Fraction(input.nextLong(), input.nextLong()); // We do not use before again, so okay to subtract in-place. before.subtract(current); sum.add(before); output.println("The difference is " + before + "."); before = current; // Remember current now as previous one. } output.println("The sum of the differences is " + sum + "."); } }