// Marty Stepp, CSE 142, Autumn 2008 // This program demonstrates a cumulative sum. // It is an enhanced version of the Receipt program we wrote in our // ch02-1 lecture about expressions and variables. // This version of the program prompts for the number of people who ate and // for each person's meal price, and computes the overall // meal cost. // // Example output: /* How many people ate? 4 Person #1: How much did your dinner cost? 20 Person #2: How much did your dinner cost? 15 Person #3: How much did your dinner cost? 25 Person #4: How much did your dinner cost? 10 Subtotal: $70.00 Tax: $5.60 Tip: $10.50 Total: $86.10 */ import java.util.*; public class Receipt2 { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How many people ate? "); int people = console.nextInt(); // "cumulative sum" : increases incrementally inside the loop double subtotal = 0.0; for (int i = 1; i <= people; i++) { System.out.print("Person #" + i + ": How much did your dinner cost? "); double personCost = console.nextDouble(); subtotal = subtotal + personCost; // add to sum } results(subtotal); } // Calculates total owed, assuming 8% tax and 15% tip public static void results(double subtotal) { double tax = subtotal * .08; double tip = subtotal * .15; double total = subtotal + tax + tip; System.out.printf("Subtotal: $%.2f\n", subtotal); System.out.printf("Tax: $%.2f\n", tax); System.out.printf("Tip: $%.2f\n", tip); System.out.printf("Total: $%.2f\n", total); } }