Yes. The program could use:
userInput.matches("[Qq](uit)?");
This could be improved by allowing extra characters (see below).
Say that a program continuously prompts the user for integer input, and prints the square root of the integer If the user enters an acceptable exit command, the program exits. If the user enters something other than an integer or exit command, the program re-prompts. Here is the program:
import java.util.Scanner; public class SquareRootPractice { private static boolean exitProgram(String user) { return user.matches(" *[Qq](uit)?.*"); } private static boolean goodNumber(String user) { return user.matches(" *[0-9]+ *"); } public static void main ( String[] args ) { Scanner scan = new Scanner( System.in ); String user; System.out.println("Enter first integer:"); user = scan.nextLine(); while ( !exitProgram( user ) ) { if ( goodNumber( user ) ) { int value = Integer.parseInt( user.trim() ); System.out.println("Square Root: " + Math.sqrt( (double)value ) ); } else System.out.println("Positive integers only, please."); System.out.println("Enter an integer:"); user = scan.nextLine(); } }
The program has been made user friendly without too much extra effort.
By using regular expressions, the program can inspect the user input
and decide what to do by pattern matching.
Notice how the string user
is used several times:
user
is checked to see if it is an exit command.
int
Here is a sample dialog:
$ java SquareRootPractice Enter first integer: 45 Square Root: 6.708203932499369 Enter an integer: -3 Positive integers only, please. Enter an integer: 3 Square Root: 1.7320508075688772 Enter an integer: q $
If the user enters 123 (not including the quote marks) what will happen?