// 10/16/2017 /** more ways of using While loop */ import java.util.Scanner; public class WhileLoopMore { /** */ public static void main(String[] args) { // example1: we know how many times to execute int number=5; // loop will execute 'number' times while (number > 0) { System.out.println("Hello, number is now: " + number); number--; } // end of while loop Scanner in = new Scanner(System.in); // example2a: we ask the user whether they want to continue String answer="Y"; //while (answer.charAt(0)=='Y' || answer.charAt(0)=='y') { // continues only if user enters Y while (answer.charAt(0)!='N' && answer.charAt(0)!='n') { // this loop will execute as long as the user enters anything // other than 'N' // play a game... System.out.println("playing game..."); System.out.print("Do you want to continue (Y for yes, N for no): "); answer=in.nextLine(); } // example2b: we ask the user whether they want to continue // this one works with a boolean variable boolean done=false; while (!done) { System.out.println("playing game loop 2..."); System.out.print("Do you want to continue (Y for yes, N for no): "); answer=in.nextLine(); //if (!(answer.charAt(0)=='Y' || answer.charAt(0)=='y')) //if (answer.charAt(0)!='Y' && answer.charAt(0)!='y') if (answer.charAt(0)=='N' || answer.charAt(0)=='n') done=true; } // while loop with sentinel System.out.println("entering while loop with sentinel."); // structured read loop int idnum; // one read BEFORE enter while loop System.out.print("Enter idnum (-1 to exit): "); idnum = in.nextInt(); while (idnum!=-1) { System.out.println("iterating while loop again..."); // another read at the END of the while loop System.out.print("Enter idnum (-1 to exit): "); idnum = in.nextInt(); } // validate a grade double grade; System.out.print("Enter a grade: "); grade = in.nextDouble(); // while the grade is not in range, ask for another input //while (grade<1 || grade>100) while (! (grade>=1 && grade<=100)) { System.out.println("that grade is invalid."); System.out.print("Enter a grade: "); grade = in.nextDouble(); } // valid, fall out of loop } }