import java.util.Scanner; public class WhileLoop { public static void main(String[] args) { // LOOP: tells your machine to print "Hello World" 5 times // begin loop: int count = 1; while (count <= 5) { System.out.println("Hello World (" + count + ")"); count++; } // convert the above while to a for loop // for (initialization; condition; update) System.out.println("for loop is executing: "); int i; for (i=0; i<5; i++) { System.out.println("Hello World (" + i + ")"); } System.out.println("when I fall out of for loop is is: " + i); // end loop // this loop does the same thing just it counts down int limit = 5; while (limit > 0) { System.out.println("Hello World (" + limit + ")"); limit--; } Scanner sc = new Scanner(System.in); System.out.println("How many times do you want to loop? "); limit = sc.nextInt(); count = 1; // use count to count up to the limit while (count <= limit) { System.out.println("count: " + count++); } // algorithm for summing // sum up all the numbers that I read in /* System.out.println("Enter next number: "); int num, sum=0; while (sc.hasNext()) { num=sc.nextInt(); sum+=num; System.out.println("Enter next number: "); } System.out.println("sum is: " + sum); sc.close(); */ // do while // executes once before condition is tested Scanner keyboard = new Scanner(System.in); int choice; do { System.out.println("Phone Plan Menu:\n1. Option 1\n4. Exit"); choice = keyboard.nextInt(); }while(choice!=4); // input validation // while input is not valid // have the user enter a different input // data value has to be between 1 and 100 System.out.println("Enter next piece of data (1-100): "); int data = keyboard.nextInt(); while (data < 1 || data > 100) { System.out.println("Data is not valid, try again (1-100): "); data = keyboard.nextInt(); } // Here's an example of a while loop that does not count /* while (guess != myNumber) { // enter another guess } boolean youWon=false; while (!youWon) { // enter another guess if (guess==myNumber) youWon=true; }// end while loop **/ // show Math.random for Assignment 3 double number = Math.random() * 100; // moves decimal pt over twice int myNumber = (int)number; // casting to an int // write a while loop that will ask the user to enter a character // and will terminate when the user enters 'n' for no // count number of iterations /** count = 0; char myChar = 'y'; while (myChar != 'n') { System.out.println("Enter a char# " + count +", n to finish:"); myChar = sc.next().charAt(0); count++; } System.out.println("count is: " + count); **/ } }