import java.util.Scanner;
/**********************************************************************
 * Class purpose: This class demonstrates the indefinite loop (while)
 *						another indefinite loop (do while)
 * 					and a counted loop (for)
 *                Terminal value used to control loop operation.
 * 
 * @author  Nancy Harris
 * @version 10/12/2008
 *********************************************************************/
public class Loopy
{
   /******************************************************************
    * Function purpose: Main will be used to demonstrate 
	 *  each of the 3 different kinds of loops 
    *
    * @param args Command line arguments, ignored
    *****************************************************************/
   public static void main(String [] args)
   {
		Scanner stdin;
		int	 sum;
		int    count;
		int	 inputVal;
		
		stdin = new Scanner(System.in);
		
		// START WITH THE WHILE LOOP
		System.out.printf ("Input positive numbers (enter a negative to end): ");

		// sum is an accumulator. Must be initialized outside of the loop
		sum = 0;		// initialization
		count = 0;
		
		if (stdin.hasNextInt())
		{
			inputVal = stdin.nextInt();	// initialization
		}
		else
		{
			// consume the bad value
			System.out.println(stdin.nextLine() + " is not an integer. Ending");
			inputVal = -1;  				// end 
		}	
		while (inputVal >= 0) 			// decision
		{
			count = count + 1;			// count only if good value
			// count++;
			sum = sum + inputVal;  		// body
			
			if (stdin.hasNextInt()) 	// body and update
			{
				inputVal = stdin.nextInt();
			}
			else
			{
				// consume the bad value
				System.out.println(stdin.nextLine() + " is not an integer. Ending");
				inputVal = -1;  				// end 
			}
		}
		System.out.printf("Sum is %d\n", sum);
		System.out.printf("Count is %d\n\n", count);
			
		// END WHILE, START DO WHILE
		sum = 0;			// initialization
		count = 0;		// "

		System.out.printf ("Enter 5 integers: ");
		do		// do says to execute the body at least one time.
		{
			if (stdin.hasNextInt())		//guard against non-ints
			{
				inputVal = stdin.nextInt();
				sum = sum + inputVal;
				count++;
			}
			else
			// note, we are still going for 5 numbers.  If we get a bad one,
			// we don't increment the counter
			{
				System.out.println(stdin.next() + " is not an integer. Try again.");
			}
		} while (count < 5);

		System.out.printf("Sum is %d\n", sum);
		System.out.printf("Count is %d\n\n", count);
		
			
		// END DO WHILE  START FOR
		
		System.out.printf ("Counting\n\n");
		sum = 0;

		// for loop includes initialization, decision and update in header
		// we loop 5 times and count the numbers from 0 to 5
		for (int ii = 1; ii <= 5; ii++)
		{
			sum = sum + ii;
			System.out.println(ii);	
		}
	}
}
