/**
 * TestLoop.java -- this is an application/main class that tests the use of
 * loops: while, do-while, and for.
 * 
 * CSCE 155 Fall 2005
 * @author Leen-Kiat Soh
 * @version 1.0
 */

import java.util.*;

class TestLoop  {

   public static void main(String[] args)  {

      // a simple for loop that iterates 10 times
      int i;
      for (i = 0; i < 10; i++)
	 System.out.println("i = " + i);

      // a simple while loop that iterates 10 times
      int j;
      j = 0;
      while  (j < 10)  {
	 System.out.println("j = " + j);
	 j++;
	 }

      // a simple do-while loop that iterates 10 times
      int k = 0;
      do {
	 System.out.println("k = " + k);
	 k++;
      }  while (k < 10);

      // Use of the sentinel-controlled loop!!
      // The loop iterates until a condition becomes true; thus we do not know
      // exactly how many times it will loop
     
      Scanner myScanner = new Scanner(System.in);   // setup console interaction
      int SECRET = Integer.parseInt(args[0]);       // argument from command
      boolean found = false;
      while (!found)  {
	 System.out.println("Please enter a number");
	 int number = myScanner.nextInt();
	 if (number == SECRET)                     // time to exit loop
	    found = true;
      }  // end while 
	 
      // This is a conversion of the above while loop into a for loop.  See,
      // even though for loops are usually used to implement count-controlled
      // loops, it can be used to implement sentinel-controlled loops as well.
      // But of course, it's unnatural and not intuitive.  This is just an
      // example to show it can be done; but it should not be done unless
      // necessary.
      for (;!found;)  {
	 System.out.println("Please enter a number");
	 int number = myScanner.nextInt();
	 if (number == SECRET)
	    found = true;
      }  // end for

      // This is an example to show we can have both sentinel- and count-control
      // for the same loop.  In the following, the number of times the loop
      // iterates is at most 10 (count-controlled) and only when a condition 
      // is true (okay)
      boolean okay = true;
      for (i = 0; i < 10 && okay; i++)  {
         System.out.println("i = " + i);
         if (i > Integer.parseInt(args[0]))
            okay = false;
      }  // end for

   }  // end main

}  // end TestLoop class


