CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Validate

Validate input data
Validate data
Generic methods to validate an entry

A method that gets a valid numeric format


public static double getDouble(Scanner sc, String prompt)
{
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
        System.out.print(prompt);
        if (sc.hasNextDouble())
        {
            d = sc.nextDouble();
            isValid = true;
        }
        else
        {
            System.out.println("Error! Invalid number. Try again.");
        }
        sc.nextLine();
            // discard any other data entered on the line
    }
    return d;
}

A method that checks for a valid numeric range


public static double getDoubleWithinRange(Scanner sc, String prompt,
double min, double max)
{
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
        d = getDouble(sc, prompt);  // call the getDouble method
        if (d <= min)
        {
            System.out.println(
                "Error! Number must be greater than " + min + ".");
        }
        else if (d >= max)
        {
            System.out.println(
                "Error! Number must be less than " + max + ".");
        }
        else
            isValid = true;
    }
    return d;
}

Code that gets valid double values using the getDouble and getDoubleWithinRange methods

Scanner sc = new Scanner(System.in);
double subtotal1 = getDouble(sc, "Enter subtotal: ");
double subtotal2 = getDoubleWithinRange(sc, "Enter subtotal: ", 0, 10000);
import java.util.Scanner;
import java.util.InputMismatchException;

public class InvoiceApp5
{
    public static void main(String[] args)
    {
        // welcome the user to the program
        System.out.println("Welcome to the Invoice Total Calculator");
        System.out.println();  // print a blank line

		// create a Scanner object named sc
		Scanner sc = new Scanner(System.in);

        // perform invoice calculations until choice isn't equal to "y" or "Y"
        String choice = "y";
        while (choice.equalsIgnoreCase("y"))
        {
			double subtotal = getDoubleWithinRange(sc, "Enter subtotal: ", 0, 10000);
        	// calculate the discount amount and total
        	double discountPercent= 0.0;
        	if (subtotal >= 200)
        		discountPercent = .2;
        	else if (subtotal >= 100)
        		discountPercent = .1;
        	else
        		discountPercent = 0.0;
        	double discountAmount = subtotal * discountPercent;
        	double total = subtotal - discountAmount;

            // display the discount amount and total
        	String message = "Discount percent: " + discountPercent + "\n"
        	               + "Discount amount:  " + discountAmount + "\n"
                           + "Invoice total:    " + total + "\n";
        	System.out.println(message);

        	// see if the user wants to continue
        	System.out.print("Continue? (y/n): ");
        	choice = sc.next();
        	System.out.println();
		}
    }

    // A method that gets a valid numeric format
    public static double getDouble(Scanner sc, String prompt)
	{
	    double d = 0.0;
	    boolean isValid = false;
	    while (isValid == false)
	    {
	        System.out.print(prompt);
	        if (sc.hasNextDouble())
	        {
	            d = sc.nextDouble();
	            isValid = true;
	        }
	        else
	        {
	            System.out.println("Error! Invalid number. Try again.");
	        }
	        sc.nextLine();
	            // discard any other data entered on the line
	    }
	    return d;
	}

	//A method that checks for a valid numeric range
	public static double getDoubleWithinRange(Scanner sc, String prompt,
	double min, double max)
	{
	    double d = 0.0;
	    boolean isValid = false;
	    while (isValid == false)
	    {
	        d = getDouble(sc, prompt);  // call the getDouble method
	        if (d <= min)
	        {
	            System.out.println(
	                "Error! Number must be greater than " + min + ".");
	        }
	        else if (d >= max)
	        {
	            System.out.println(
	                "Error! Number must be less than " + max + ".");
	        }
	        else
	            isValid = true;
	    }
	    return d;
	}
}

Previous | Prevent exceptions from being thrown | Validate a single entry | Generic methods to validate an entry | Next