Simple Data Validation

Things To Do Before Class

Things To Do After Class

Validating User Input

When you ask a user to input data, you should always validate that data and make sure it's correct. Never assume that the user will enter the data correctly, even if you give clear instructions (users don't often read instructions :P )

Copy and paste the following program into your editor:

import java.util.Scanner;

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

        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter the number of items in inventory: ");
        int numItems = in.nextInt();
        System.out.print("Enter the cost per item: ");
        double itemCost = in.nextDouble();
        
        double totalCost = numItems * itemCost;
        
        System.out.printf("Total Cost: $%.2f%n", totalCost);
    }
}

What kinds of things could go wrong in this program? What kinds of user-entered values would crash the program?

If you're not sure, try entering the following:

Which sets of input values crash the program?

Which sets of input values produce output that doesn't make sense?

There are two kinds of problems here:

  1. The user could enter a value that isn't compatible with the data type being retrieved. e.g. entering non-digits or entering a decimal value for the number of items.
  2. The user could enter values that don't make sense, like 0 or negative values.

Solving problem #1 is beyond the scope of this lesson, but we'll learn a few solutions when we do the Exception Handling Lesson.

The second problem can be solved with some simple if-statements and loops.

Exercise

[Solutions]

1. Modify the above program: if the number of items entered is 0 or negative, display an error message. If the number of items is valid, go ahead and ask for the price. If the price is 0 or negative, display an error message. If the price is valid, go ahead and calculate/display the total cost. The total cost should only be calculated and displayed if both inputs are positive, non-zero values.

2. What if we wanted the program to continue running, and just ask the user over and over again for the inputs until those inputs are entered correctly? We can include a loop to do this:

Write a program that validates an integer value. The value must be positive. Write a loop that iterates as long as the user-entered integer is not valid. Make sure you display an error message. The easiest way to do this is using the priming read/continuing read structure:

DISPLAY "Enter a positive whole number:"
GET number

WHILE (number &tl;= 0)
    DISPLAY "Error: " + number + " is not a positive number."
    DISPLAY "Try again:"
    GET number
DISPLAY "You entered the valid number " + number

In the pseudocode above, the first DISPLAY/GET is the "priming read": we do an initial read to prime (set up) the number variable.

Inside the loop, we use a "continuing read" to read the number from the user again - this allows the loop to continue iterating as long as the value is invalid, and stop iterating when the value is valid. Without the continuing read, we'd have an endless loop.

Once the loop has terminated, you know the user input is valid: the loop will not terminate until the user has entered a value that matches your criteria.

Use this technique to get a positive number from the user.

3. Modify question 1 to ask the user repeatedly until they enter the number of items and price correctly. Include user-friendly error messages. Only calculate/display the total cost if the price and number of items are valid.

4. Write a program that asks the user for a latitude value and a longitude value. A valid latitude value must be between -90 and 90, inclusive. A longitude value must be between -180 and 180, inclusive. Keep prompting the user to enter valid values until they get them both correct. Include user-friendly error messages. Once the latitude and longitude are entered correctly, display the latitude and longitude as coordinates, formatted to 6 decimal places (e.g. (43.469210, -79.700271)).