- Forward


Reprompting
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Frequently:
    • We need to prompt a user to provide input, validate the input and re-prompt if the input is invalid
  • Variants:
    • The initial prompt and the subsequent prompts are different
    • All prompts are the same
Motivation (cont.)
Back SMYC Forward
  • The Most Obvious Approach:
    • Use an if statement to validate and re-prompt
  • An Example in Pseudocode:
    • Prompt the user to enter their age; Read the user's response; Assign the response to the variable named age; if (age is negative) { Prompt the user to enter their age; Read the user's response; Assign the response to the variable named age; } Use the variable named age;
  • A Shortcoming of this Approach:
    • The user may need to be re-prompted multiple times for the same input
Review
Back SMYC Forward
  • What's Needed:
    • A way to repeat a block of code an indefinite number of times (i.e., until the user enters a valid response)
  • What Should be Brought to Mind:
    • while and do loops
The Pattern with Identical Prompts
Back SMYC Forward
  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
Back SMYC Forward
  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
Back SMYC Forward
javaexamples/programmingpatterns/reprompt/RepromptJMUConsole.java (Fragment: identical)
 
An Example with Different Prompts
Back SMYC Forward
javaexamples/programmingpatterns/reprompt/RepromptJMUConsole.java (Fragment: different)
 
There's Always More to Learn
Back -