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.

6. while Loop Version


See below.

while Loop Version

The first iteration of the loop body can be made to happen by initializing chars to "yes." This is slightly awkward.

import java.util.Scanner;

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

    chars = "yes" ;        // enable first iteration of the loop

    while ( chars.equals( "yes" ) )
      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 6:

Examine the code (again.) How would it be written with a for loop?