Answers – Input Validation – CS2 – Java

Program 1

2. List the potential input validation errors.

The index used returned by getWhich is not validated, Also, if a non-integer value is typed for prompts in getArraySize() and getWhich(), an exception will be thrown. The value returned by getArraySize() is not checked for reasonableness – it might be absurdly large.

3. Provide example inputs that might cause validation problems, and describe the problems that they might cause.

If the number typed for getWhich() is greater than the number provided for getArraySize(), or it is less than zero the value passed to getName() will be out of bounds, and an ArrayIndexException will be thrown.

See next question as well.

4. What happens if you type non-numeric characters for either the number of names or which name you wanted to retrieve?

An Exception will be thrown.

5.Revise the program to properly validate input and gracefully recover from errors.

import java.util.*;

public class Input2 {
  public static void main(String[] args) {

    Scanner scan = new Scanner(;
    int sz = getArraySize(scan);
    String[] names = getNames(scan,sz);
    int which = getWhich(scan,names.length);    
    String aName = getName(which,names);
    System.out.println("You choose name: "+aName);
  public static int getArraySize(Scanner scan) {
    int n = -1;
    while ( n  length) {
      try {
        System.out.print("Which name: ");
        x = scan.nextInt();
      catch(InputMismatchException e) {
        System.out.println("Please type an integer value");
    return x;
  public static String getName(int n,String[] vals) {
    if (n >=1 && n 

The original program did not validate the name for format or length, and neither does this version. Validating names is extremely difficult, as puncuation characters, digits, and other non-alphabetic characters might appear.

Program 2

import java.util.Scanner;

public class Auction {
  public static void main(String[] args) {
    Scanner scan = new Scanner(;
    boolean priceValid = false;
    boolean quantValid = false;
    String priceString="";
    String quantString="";
    float price=0.0f;
    int quant = 0; 
    while (priceValid == false || quantValid == false) {
      if (priceValid == false) {
        priceString =  getPriceString(scan);
        priceValid =  validatePrice(priceString);
        if (priceValid == true) {
          price = Float.parseFloat(priceString);
      if (quantValid == false) {
        quantString = getQuantString(scan);
        quantValid = validateQuant(quantString);
        if (quantValid == true) {
          quant = Integer.parseInt(quantString);
      if (priceValid == false) {
        System.out.println("Not a valid price. Prices must be of the form "12.45"n");
      if (quantValid == false) {
        System.out.println("Not a valid quantity. Quantity must be a whole number greater than zero.");
  public static String getPriceString(Scanner scan) {
    return getStringValue("Please type the price that you are willing to pay: ",scan);
  public static String getQuantString(Scanner scan) {
    return getStringValue("Please indicate the number of items that you wish to purchase: ",scan);
  public static String getStringValue(String msg,Scanner scan) {
    String value =;
    return value;
  public static  boolean validatePrice(String price) {
    int decimalCount = 0;
    boolean seenDigit = false;
    for (int i=0; i ='0' && c 0
    int quan = Integer.parseInt(q);
    if (quan 1) {
      item +="s";
    String msg = "You are buying "+q+" "+item+" at $"+p;
    if (q > 1) {
      msg +=" each";

1. You’re writing a program that asks the user to type in a telephone number. How might you validate that the characters that they’ve typed represent a legal telephone number? You should assume that you’re only concerned about phone numbers from the US, but you want to give users as much flexibility as possible, in terms of spaces and punctuation characters. List some rules that you might use. Make sure that you complete this question before moving on to question #2.

  1. Verify that there are 10 digits
  2. Remove any parentheses, dashes, or spaces

2. Find an example of a phone number that doesn’t fit your rules.

Anything that requires a leading 1 – as in 1 410 555 1212

Any number specified with a “+” at the beginning: +1 410 555 1212

3. Describe either an example of an input validation problem that you may have encountered. If you can’t remember having any sort of problem, try some web pages or other software tools – try to find a system that fails to validate input data correctly.

Taking zip codes without verifying 5 digits, accepting dates that have already passed, improper formats for phone numbers, etc.

Further Work

1. If input is sufficiently cryptic, it might be hard to provide useful error messages in responses to invalid input. Describe some strategies that might be used to help users recover from invalid input.

Example formats indicating what correct inputs might look like, error messages that describe difficulties with input as provided. Flexible inputs that allow users to correct multiple errors with one screen – as opposed to fixing them one at a time.

2. Revisit Program 2. Are there any inputs that the above description accepts as valid that perhaps should be considered invalid? If so, what are they and how might you handle them?

The price can accept value with three numbers after the decimal point, such as 12.345. This should probably be modified so that the number of cents is required to be whole.

View more information:

See more articles in category: Grammar
READ:  Michael McGuire | Towson University

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button