//WhileLoopsDemo.java import java.awt.*; import javax.swing.*; public class WhileLoopsDemo extends JApplet { public void static main(String[] argv) { //public void init() { String input; int n; double num; //Loop until the user wants to stop. //does not ask up front how many numbers. //A particular value ("sentinel") will be used to indicate the end of input. //while loop is better than for loop for this "indefinite iteration". //Use for loop when know how many times to loop: "N" times. //"priming read" to get first number: input = JOptionPane.showInputDialog("Enter number for square rooting" + " (0 to quit)"); num = Double.parseDouble( input ); while (num != 0) { //0 will be "sentinel" that indicates end of input if (num > 0) JOptionPane.showMessageDialog(null, "square root is " + Math.sqrt(num) ); else JOptionPane.showMessageDialog(null, "No square root of negative number" ); //get next number (at bottom of loop, typically) input = JOptionPane.showInputDialog( "Enter a number for square rooting" + " (0 to quit)"); num = Double.parseDouble( input ); } //************************************************** //"error-checking/data validation loop" to ensure valid input //Note that these booleanExpressions are the same examples from our if examples. input = JOptionPane.showInputDialog("Enter a number between 1 and 5"); n = Integer.parseInt( input ); while (n<1 || n>5) { // while bad input input = JOptionPane.showInputDialog( "Invalid." + "Must be between 1 and 5\n" + "Enter a number between 1 and 5" ); n = Integer.parseInt( input ); } //after the loop, the num is valid, ie. between 1 and 5... JOptionPane.showMessageDialog(null, "Thanks for " + n ); //************************************************** input = JOptionPane.showInputDialog( "Enter: 1, 5, or 8" ); n = Integer.parseInt( input ); while (n!=1 && n!= 5 && n!=8) { //while not 1 AND not 5 AND not 8 input = JOptionPane.showInputDialog("Invalid. Must be 1 or 5 or 8\n" + "Enter 1, 5 or 8" ); n = Integer.parseInt( input ); } //after the loop, the num is valid, ie. 1, 5 or 8... JOptionPane.showMessageDialog(null, "Thanks for " + n ); //************************************************** String name; name = JOptionPane.showInputDialog( "Enter choice: Bob or Jane" ); while (!name.equalsIgnoreCase("bob") && !name.equalsIgnoreCase("jane")) name = JOptionPane.showInputDialog( "Invalid. Must be Bob or Jane\n" + "Enter again:" ); JOptionPane.showMessageDialog(null, "Thanks for " + name ); //*********************************************** int i=0; while (true) { //infinite loop System.out.println("i= " +i); i++; } } } /* no braces on bob... ; after bob... show problems if while (n!=1 || */