The Do Statement

The 'do-while' loop is a variation of the while loop. 'do-while' loops always execute at least once, whereas while loops may never execute.

7. for Loop Version


See below.

for Loop Version

The for loop version also seems awkward. You have to remember that the "change" part of the for statement can be omitted. This is correct syntax, but now you must be careful to make the change in the loop body.

Of course, the biggest problem with all three versions is that the user must type exactly "yes" for the program to continue. Better programs would allow "y" or "Y" or "YES" .

import* ;
public class SqrtCalc
  public static void main( String[] args )
    String chars;
    double x;
    Scanner scan = new Scanner( );

    for ( chars = "yes"; chars.equals( "yes" );  )  // last part of "for" omitted
    {                                               // (this is OK)
      System.out.print("Enter a number-->");
      x = scan.nextDouble(); 
      chars = scan.nextLine();   // flush rest of the line
      System.out.println("Square root of " + x + " is " + Math.sqrt( x ) );
      System.out.print("Do you wish to continue? (yes or no) --> ");
      chars = scan.nextLine();


Question 7:

You want the program to continue when the user to enters any of the following:

    1. yes
    2. YES
    3. Y
    4. y

The program should quit for anything else. How (in general) can you do this?