/* CSE 142, Spring 2010 This program prompts the user for text until a given special "sentinel" value is typed, then displays the sum of the lengths of the text. This is an example of a sentinel loop, which is also an example of a fencepost problem. Example output: Type a line (or "quit" to exit): hello Type a line (or "quit" to exit): this is a line Type a line (or "quit" to exit): quit You typed a total of 19 characters. */ import java.util.*; // for Scanner public class Sentinel { public static final String SENTINEL = "quit"; public static void main(String[] args) { Scanner console = new Scanner(System.in); // read text from scanner until we see the sentinel // 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 a line // "wires" - add the line lengths to a cumulative sum System.out.print("Type a line (or \"" + SENTINEL + "\" to exit): "); String response = console.nextLine(); while (!response.equals(SENTINEL)) { sum += response.length(); System.out.print("Type a line (or \"" + SENTINEL + "\" to exit): "); response = console.nextLine(); } System.out.println("You typed a total of " + sum + " characters."); } }