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.

9. Program with Alternatives


Answer:

The || (or operator) is the appropriate choice:

while ( chars.equals( "yes" ) || chars.equals( "YES" ) ||  
        chars.equals( "y" )   ||  chars.equals( "Y" )   )

Program with Alternatives


import java.util.Scanner;

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

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

    while ( chars.equals( "yes" || chars.equals( "YES" ) ||  
            chars.equals( "y" ) ||  chars.equals( "Y" )  )
    {
      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();
   }

  }
}

Since any one choice is all we need, the OR operation is the appropriate way to combine the choices.

Another possiblility is to use some other methods of String: the String.toUpperCase() could convert the input to all capitals, then String.startsWith("Y") could test the first character.

The program is still not as user friendly as it could be. If the user types an invalid number in response to the prompt, an exception is thrown and the program halts and prints error messages.

Ordinary users would not like to see this. But improving the program requires the exception handling techniques discussed in chapter 100, so let's not do that now.


Question 9:

Do you wish to continue?