1 // Example 2.1 While1Demo.java 2 // 3 // 4 // Copyright 2003 Bill Campbell and Ethan Bolker 5 6 // A class for illustrating the while-statement. A typical run: 7 // 8 // %> java While1Demo 9 // Enter integer (a negative to stop): 4 10 // 4 is non-negative. 11 // Enter integer (a negative to stop): -3 12 // 13 // Enter integer (a negative to stop): 5 14 // 5 is non-negative. 15 // Enter integer (a negative to stop): -2 16 // Finally, enter integer you want to count to: 12 17 // Count 1 to 12: 1 2 3 4 5 6 7 8 9 10 11 12 18 19 public class While1Demo 20 { 21 public static void main( String[] args ) 22 { 23 Terminal terminal = new Terminal(); // for input and output 24 25 // while tests a condition 26 int n = terminal.readInt("Enter integer (a negative to stop): "); 27 while ( n >= 0 ) { 28 terminal.println( n + " is non-negative." ); 29 n = terminal.readInt("Enter integer (a negative to stop): "); 30 } 31 terminal.println(); 32 33 // while tests a boolean variable 34 boolean more = true; 35 while ( more ) { 36 n = terminal.readInt("Enter integer (a negative to stop): "); 37 if ( n >= 0 ) { 38 terminal.println( n + " is non-negative." ); 39 } 40 else { 41 more = false; 42 } 43 } 44 45 // while used for counting 46 n = terminal. 47 readInt("Finally, enter integer you want to count to: "); 48 int i = 1; 49 terminal.print( "Count 1 to " + n + ":" ); 50 while ( i <= n ) { 51 terminal.print( " " + i ); 52 i++; // same as i = i + 1 53 } 54 terminal.println(); 55 } 56 }