The ||
(or operator) is the appropriate choice:
( chars.equals( "yes" ) || chars.equals( "YES" ) || chars.equals( "y" ) || chars.equals( "Y" ) )
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.
Do you wish to continue?