go to previous page   go to home page   go to next page

Answer:

Yes. The program could use:

  userInput.matches("[Qq](uit)?");

This could be improved by allowing extra characters (see below).


Checking User Input

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:

  1. First, user is checked to see if it is an exit command.
    • if so, the program exits
  2. Then, it is checked to see if it is acceptable as an integer.
    • if not, the user is re-prompted
    • if so, the string is trimmed, and converted to an 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
$

QUESTION 7:

If the user enters 123 (not including the quote marks) what will happen?