import java.util.Scanner; /** * Program to determine the average of three fractions * * @author Steven Karas */ public class FractionAverage { public static void main(String[] args) { Scanner scan = new Scanner(System.in); /* * This is a long section of code, so variable names are important. You * can see how this is much better than x1, x2, x3, etc. */ // get the fractions from the user System.out.print("Enter three fractions: "); int aNumerator = scan.nextInt(); int aDenominator = scan.nextInt(); int bNumerator = scan.nextInt(); int bDenominator = scan.nextInt(); int cNumerator = scan.nextInt(); int cDenominator = scan.nextInt(); Fraction a = new Fraction(aNumerator, aDenominator); Fraction b = new Fraction(bNumerator, bDenominator); Fraction c = new Fraction(cNumerator, cDenominator); /* * There may be other ways to determine the average. I chose to sum them * up and then divide by 3. * * Of note here is that I "chained" the calls to Fraction.add(). You * can't always do this, but it can make long blocks of code much * shorter. */ // determine the sum Fraction sum = a.add(b).add(c); // divide by 3 Fraction average = sum.divide(new Fraction(3, 1)); /* * We can just tell Java to print the Fractions because Fraction has a * special function called toString() that tells it how to format * itself. */ // output the average System.out.println("The average of " + a + ", " + b + ", and " + c + " is " + average); } }