//DoLoops.java /* do { stmts of body } while (condition); 1. does at least one iteration of loop. 2. test of condition is at end/bottom of loop. Conventional to use braces even if only one statement in the body of the loop. Do loop is useful if need loop that does body one or more times. (as oppopsed to while that iterates zero or more times) */ import java.awt.*; import javax.swing.*; public class DoLoops extends JApplet { public static void main(String[] argv) { //public void init() { String input; double num; int n; //input numbers, do square root. 0 indicates end of input. //***Need to input at least one number, so use do loop instead of //while loop. do { input = JOptionPane.showInputDialog( "Enter a number for square rooting" ); num = Double.parseDouble( input ); if (num > 0) JOptionPane.showMessageDialog(null, "square root is " + Math.sqrt(num) ); else if (num < 0) JOptionPane.showMessageDialog(null, "No square root of negative number" ); } while (num != 0); //************************************************** //"error-checking loop" to ensure valid input. //***Need to get input at least once. Use do instead of while to //avoid "priming read" before the loop. do { input = JOptionPane.showInputDialog("Enter a number between 1 and 5" ); n = Integer.parseInt( input ); if (n<1 || n>5) JOptionPane.showMessageDialog(null,"Bad input. do it again"); } while (n<1 || n>5); //after the loop, the num is valid, ie. between 1 and 5... JOptionPane.showMessageDialog(null, "Thanks for " + n ); } }