Program with Alternatives

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

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

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

Program with Alternatives

Since any one choice is all we need, the OR operation is the appropriate way to combine the choices. Here is the while loop version of the program modified in this way:

import java.util.Scanner;
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();
   }

  }
}

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 80, so let's not do that now.

QUESTION 9:

Do you wish to continue?