// Zorah Fung, CSE 142 // An example of using a while loop and a sentinel loop import java.util.*; public class WhileLoops { public static final String SENTINEL = "quit"; public static void main(String[] args) { firstPrime(); sentinelLoop(); } public static void firstPrime() { // find the first factor of 91, other than 1 int n = 91; int factor = 2; // initialization while (n % factor != 0) { // test factor++; // update } System.out.println("The first factor is: " + factor); } public static void sentinelLoop() { Scanner console = new Scanner(System.in); // all variable(s) in your while loop test // MUST be declared before/outside the while loop // fencepost problem: pull first post out int totalChars = 0; /* post */ System.out.print("Type a word (or \"" + SENTINEL + "\" to exit): "); /* post */ String word = console.next(); while (!word.equals(SENTINEL)) { /* wire */ totalChars += word.length(); /* post */ System.out.print("Type a word (or \"" + SENTINEL + "\" to exit): "); /* post */ word = console.next(); } System.out.println("The total number of characters is: " + totalChars); } }