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.

5. User Interaction


Answer:

No. A for loop is the best choice for a counting loop.

User Interaction

The previous example used the do in a counting loop. This was to show how it worked. Usually you would use a for loop. A more appropriate use of a do is in a loop that interacts with the user.

sqrtOut

import java.util.Scanner ;
public class SqrtCalc
{
  public static void main( String[] args )
  {
    String chars;
    double x;
    Scanner scan = new Scanner(System.in );

    do
    {
      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();

    }
    while ( chars.equals( "yes" ) );    

  }
}

Notice the statement that flushes the rest of the input line. This is necessary because nextDouble() reads only the characters that make up the number. The rest of the line remains in the input stream and would be what nextLine() reads if they were not flushed.


Question 5:

Examine the code. How would it be written with a while loop?