JMU
Reprompting
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Motivation (cont.)
Review
The Pattern with Identical Prompts
  1. Enter a do loop. In the body of the loop:
    1. Prompt the user.
    2. Retrieve the user's response.
  2. Repeat when the response is invalid.
The Pattern with Different Prompts
  1. Prompt the user with the normal message.
  2. Retrieve the user's response.
  3. Enter a while loop when the response is invalid. In the body of the loop:
    1. Prompt the user with the alternative message.
    2. Retrieve the user's response.
  4. Repeat.
An Example with Identical Prompts
javaexamples/programmingpatterns/reprompt/RepromptJMUConsole.java (Fragment: identical)
                do {
            JMUConsole.printf("Enter a non-negative age: ");
            age = JMUConsole.readInt();
        } while (age < 0);
        
An Example with Different Prompts
javaexamples/programmingpatterns/reprompt/RepromptJMUConsole.java (Fragment: different)
                JMUConsole.printf("Enter your age: ");
        age = JMUConsole.readInt();
        while (age < 0) {
            JMUConsole.printf("  Enter a non-negative value: ");
            age = JMUConsole.readInt();
        }