1 // Example 2.2 joi/examples/While2Demo.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 While2Demo 9 // Enter integer: 10 10 // Fibonacci numbers <= 10: 1 1 2 3 5 8 11 // Fibonacci numbers <= 10: 1 1 2 3 5 8 12 // First 10 Fibonacci numbers: 1 1 2 3 5 8 13 21 34 55 13 14 public class While2Demo 15 { 16 public static void main( String[] args ) 17 { 18 Terminal terminal = new Terminal(); // for input and output 19 20 // Prompt for and read a single integer. 21 int n = terminal.readInt( "Enter integer: " ); 22 23 // while tests a condition 24 terminal.print( "Fibonacci numbers <= " + n + ":" ); 25 int thisOne = 1; 26 int lastOne = 1; 27 while ( lastOne <= n ) { 28 terminal.print( " " + lastOne ); 29 int nextOne = thisOne + lastOne; 30 lastOne = thisOne; 31 thisOne = nextOne; 32 } 33 terminal.println(); 34 35 // while tests a boolean variable 36 terminal.print( "Fibonacci numbers <= " + n + ":" ); 37 thisOne = 1; 38 lastOne = 1; 39 boolean more = true; 40 while ( more ) { 41 if ( lastOne > n ) { 42 more = false; 43 } 44 else { 45 terminal.print( " " + lastOne ); 46 int nextOne = thisOne + lastOne; 47 lastOne = thisOne; 48 thisOne = nextOne; 49 } 50 } 51 terminal.println(); 52 53 // while used for counting 54 terminal.print( "First " + n + " Fibonacci numbers:" ); 55 thisOne = 1; 56 lastOne = 1; 57 int i = 1; 58 while ( i <= n ) { 59 terminal.print( " " + lastOne ); 60 int nextOne = thisOne + lastOne; 61 lastOne = thisOne; 62 thisOne = nextOne; 63 i++; // same as 'i = i + 1;' 64 } 65 terminal.println(); 66 } 67 }