/* Marty Stepp, CSE 142, Autumn 2009 This program prompts the user for numbers until a given special "sentinel" value is typed, then displays the sum of the numbers. This is an example of a sentinel loop, which is also an example of a fencepost problem. Example output: Enter a number (-1 to quit): 10 Enter a number (-1 to quit): 20 Enter a number (-1 to quit): 30 Enter a number (-1 to quit): -1 The sum is 60 */ import java.util.*; // for Scanner public class SentinelSum { public static final int SENTINEL = -1; public static void main(String[] args) { Scanner console = new Scanner(System.in); // read ints from scanner until we see a 0 // any variable(s) used in your while loop test must be declared BEFORE the loop header int sum = 0; // fencepost loop; move one "post" out of the loop // "posts" - prompt/read an int // "wires" - add them to a cumulative sum System.out.print("Enter a number (" + SENTINEL + " to quit): "); int n = console.nextInt(); while (n != SENTINEL) { sum += n; // sum = sum + n; sum *= n; sum = sum * n; System.out.print("Enter a number (" + SENTINEL + " to quit): "); n = console.nextInt(); } System.out.println("The sum is " + sum); } }