How to handle invalid user input in a Java program

JavaJavaBeginner
Practice Now

Introduction

Handling invalid user input is a crucial aspect of Java programming that ensures your applications remain robust and reliable. When users interact with your programs, they may provide unexpected or incorrect data that could cause your application to crash if not properly managed.

In this lab, you will learn how to effectively handle invalid user input in Java applications. You will explore different techniques, from basic error checking to more advanced validation methods. By the end of this lab, you will be able to write Java programs that gracefully handle user errors and provide appropriate feedback.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/StringManipulationGroup -.-> java/regex("RegEx") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("User Input") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("Encapsulation") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") subgraph Lab Skills java/if_else -.-> lab-414054{{"How to handle invalid user input in a Java program"}} java/regex -.-> lab-414054{{"How to handle invalid user input in a Java program"}} java/user_input -.-> lab-414054{{"How to handle invalid user input in a Java program"}} java/encapsulation -.-> lab-414054{{"How to handle invalid user input in a Java program"}} java/exceptions -.-> lab-414054{{"How to handle invalid user input in a Java program"}} end

Creating a Basic Java Program with User Input

In this first step, we will create a simple Java program that collects user input. This will serve as a foundation for learning input validation techniques.

Understanding User Input in Java

Java provides several ways to collect input from users. For console applications, the Scanner class from the java.util package is commonly used. This class offers methods to read different types of input, such as integers, floating-point numbers, and strings.

Creating the Input Program

Let's start by creating a basic Java program that asks for a user's age and prints it back.

  1. First, open the WebIDE and navigate to the project directory:

  2. Create a new file by clicking on the "New File" icon in the WebIDE's file explorer. Name the file UserInputDemo.java

  3. Add the following code to the file:

import java.util.Scanner;

public class UserInputDemo {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        // Prompt the user for their age
        System.out.print("Please enter your age: ");

        // Read the input
        int age = scanner.nextInt();

        // Display the entered age
        System.out.println("You entered: " + age);

        // Close the scanner
        scanner.close();
    }
}
  1. Save the file by pressing Ctrl+S or selecting "File" > "Save" from the menu.

  2. Open a terminal in the WebIDE by clicking on "Terminal" > "New Terminal" from the top menu.

Input Demo
  1. Compile the Java program by running the following command:
javac UserInputDemo.java
  1. Run the program with:
java UserInputDemo
  1. Enter a number when prompted, for example, 25. You should see the following output:
Please enter your age: 25
You entered: 25

What Happens with Invalid Input?

Now, let's see what happens when we provide invalid input. Run the program again:

java UserInputDemo

This time, enter a non-numeric value, such as twenty-five. You will see an error message similar to:

Please enter your age: twenty-five
Exception in thread "main" java.util.InputMismatchException
 at java.base/java.util.Scanner.throwFor(Scanner.java:943)
 at java.base/java.util.Scanner.next(Scanner.java:1598)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
 at UserInputDemo.main(UserInputDemo.java:12)

This InputMismatchException occurs because the program expected a numeric input (an integer), but received text instead. The program crashes rather than handling this gracefully. In the next steps, we will learn how to handle such invalid inputs properly.

Handling Exceptions for Invalid Input

In this step, we will modify our program to handle invalid input using Java's exception handling mechanism.

Understanding Java Exceptions

Exceptions in Java are events that disrupt the normal flow of program execution. When a user provides invalid input, the Java runtime system throws an exception to signal that something went wrong. The program can catch these exceptions and handle them appropriately, rather than crashing.

The basic structure for exception handling in Java is the try-catch block:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}

Modifying Our Program to Handle Exceptions

Let's update our program to handle the InputMismatchException that occurs when the user enters non-numeric input:

  1. Open the UserInputDemo.java file in the WebIDE.

  2. Modify the code to include exception handling:

import java.util.Scanner;
import java.util.InputMismatchException;

public class UserInputDemo {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        try {
            // Prompt the user for their age
            System.out.print("Please enter your age: ");

            // Read the input
            int age = scanner.nextInt();

            // Display the entered age
            System.out.println("You entered: " + age);
        } catch (InputMismatchException e) {
            // Handle the exception if non-numeric input is provided
            System.out.println("Error: Please enter a valid numeric age.");
        } finally {
            // Close the scanner in the finally block to ensure it always gets closed
            scanner.close();
        }
    }
}
  1. Save the file by pressing Ctrl+S.

  2. Compile the updated program:

javac UserInputDemo.java
  1. Run the program:
java UserInputDemo
  1. Try entering a non-numeric value, such as twenty-five. Instead of crashing, the program now displays:
Please enter your age: twenty-five
Error: Please enter a valid numeric age.

Improving Our Exception Handling

Our current implementation handles the exception but exits immediately. Let's improve it by giving the user multiple attempts to enter a valid age:

  1. Open the UserInputDemo.java file in the WebIDE.

  2. Modify the code to allow multiple attempts:

import java.util.Scanner;
import java.util.InputMismatchException;

public class UserInputDemo {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        boolean validInput = false;
        int age = 0;

        // Keep trying until valid input is received
        while (!validInput) {
            try {
                // Prompt the user for their age
                System.out.print("Please enter your age: ");

                // Read the input
                age = scanner.nextInt();

                // If we get here, the input was valid
                validInput = true;
            } catch (InputMismatchException e) {
                // Handle the exception if non-numeric input is provided
                System.out.println("Error: Please enter a valid numeric age.");

                // Clear the invalid input from the scanner
                scanner.nextLine();
            }
        }

        // Display the entered age
        System.out.println("You entered: " + age);

        // Close the scanner
        scanner.close();
    }
}
  1. Save the file.

  2. Compile and run the program again:

javac UserInputDemo.java
java UserInputDemo
  1. Try entering an invalid input first, then a valid one:
Please enter your age: twenty-five
Error: Please enter a valid numeric age.
Please enter your age: 25
You entered: 25

Now our program gives the user multiple chances to provide valid input. This is a significant improvement in handling invalid input gracefully.

Implementing Input Validation with Conditional Statements

In addition to exception handling, we can use conditional statements to validate user input. This approach allows us to implement custom validation rules before processing the input.

Understanding Input Validation

Input validation is the process of checking user input to ensure it meets specific criteria before processing it. For example, we might want to ensure that an age value is not only a number but also within a reasonable range.

Adding Range Validation to Our Program

Let's enhance our program to validate that the user enters an age between 0 and 120:

  1. Open the UserInputDemo.java file in the WebIDE.

  2. Modify the code to include range validation:

import java.util.Scanner;
import java.util.InputMismatchException;

public class UserInputDemo {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        boolean validInput = false;
        int age = 0;

        // Keep trying until valid input is received
        while (!validInput) {
            try {
                // Prompt the user for their age
                System.out.print("Please enter your age (0-120): ");

                // Read the input
                age = scanner.nextInt();

                // Check if the age is within a valid range
                if (age < 0 || age > 120) {
                    System.out.println("Error: Age must be between 0 and 120.");
                } else {
                    // If we get here, the input was valid
                    validInput = true;
                }
            } catch (InputMismatchException e) {
                // Handle the exception if non-numeric input is provided
                System.out.println("Error: Please enter a valid numeric age.");

                // Clear the invalid input from the scanner
                scanner.nextLine();
            }
        }

        // Display the entered age
        System.out.println("You entered: " + age);

        // Close the scanner
        scanner.close();
    }
}
  1. Save the file by pressing Ctrl+S.

  2. Compile the program:

javac UserInputDemo.java
  1. Run the program:
java UserInputDemo
  1. Test the program with different inputs:

    • Enter a valid age (e.g., 25):
    Please enter your age (0-120): 25
    You entered: 25
    • Enter a negative age:
    Please enter your age (0-120): -5
    Error: Age must be between 0 and 120.
    Please enter your age (0-120):
    • Enter an age over 120:
    Please enter your age (0-120): 150
    Error: Age must be between 0 and 120.
    Please enter your age (0-120):
    • Enter a non-numeric value:
    Please enter your age (0-120): twenty-five
    Error: Please enter a valid numeric age.
    Please enter your age (0-120):

Creating a More Complex Example: User Registration Form

Let's create a more comprehensive example that validates multiple fields for a user registration form:

  1. Create a new file named UserRegistration.java in the WebIDE.

  2. Add the following code to the file:

import java.util.Scanner;

public class UserRegistration {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Get and validate username
        String username = getValidUsername(scanner);

        // Get and validate age
        int age = getValidAge(scanner);

        // Get and validate email
        String email = getValidEmail(scanner);

        // Display the registration information
        System.out.println("\nRegistration Successful!");
        System.out.println("Username: " + username);
        System.out.println("Age: " + age);
        System.out.println("Email: " + email);

        scanner.close();
    }

    private static String getValidUsername(Scanner scanner) {
        String username;
        boolean validUsername = false;

        do {
            System.out.print("Enter username (3-15 characters): ");
            username = scanner.nextLine().trim();

            if (username.length() < 3 || username.length() > 15) {
                System.out.println("Error: Username must be between 3 and 15 characters.");
            } else {
                validUsername = true;
            }
        } while (!validUsername);

        return username;
    }

    private static int getValidAge(Scanner scanner) {
        int age = 0;
        boolean validAge = false;

        while (!validAge) {
            try {
                System.out.print("Enter your age (0-120): ");
                age = Integer.parseInt(scanner.nextLine());

                if (age < 0 || age > 120) {
                    System.out.println("Error: Age must be between 0 and 120.");
                } else {
                    validAge = true;
                }
            } catch (NumberFormatException e) {
                System.out.println("Error: Please enter a valid numeric age.");
            }
        }

        return age;
    }

    private static String getValidEmail(Scanner scanner) {
        String email;
        boolean validEmail = false;

        do {
            System.out.print("Enter your email: ");
            email = scanner.nextLine().trim();

            // Simple email validation: must contain @ and a period after @
            if (!email.contains("@") || email.indexOf('.', email.indexOf('@')) == -1) {
                System.out.println("Error: Please enter a valid email address.");
            } else {
                validEmail = true;
            }
        } while (!validEmail);

        return email;
    }
}
  1. Save the file by pressing Ctrl+S.

  2. Compile the program:

javac UserRegistration.java
  1. Run the program:
java UserRegistration
  1. Follow the prompts to enter a username, age, and email. The program will validate each input and only proceed when valid data is entered.

Sample valid input sequence:

Enter username (3-15 characters): johnsmith
Enter your age (0-120): 30
Enter your email: [email protected]

Registration Successful!
Username: johnsmith
Age: 30
Email: [email protected]

This more comprehensive example demonstrates how to validate different types of user input using both exception handling and conditional validation.

Using Regular Expressions for Input Validation

Regular expressions (regex) provide a powerful way to validate complex input patterns like email addresses, phone numbers, and passwords. In this step, we will learn how to use regular expressions in Java to perform advanced input validation.

Understanding Regular Expressions

A regular expression is a sequence of characters that defines a search pattern. These patterns can be used to validate if a string conforms to a specific format. Java provides the java.util.regex package, which includes the Pattern and Matcher classes for working with regular expressions.

Adding Regex Validation to Our UserRegistration Program

Let's enhance our UserRegistration program to use regular expressions for more robust input validation:

  1. Open the UserRegistration.java file in the WebIDE.

  2. Modify the file to include regex validation:

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class UserRegistration {
    // Regular expression patterns
    private static final String USERNAME_PATTERN = "^[a-zA-Z0-9_]{3,15}$";
    private static final String EMAIL_PATTERN = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    private static final String PHONE_PATTERN = "^\\d{3}-\\d{3}-\\d{4}$";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Get and validate username
        String username = getValidUsername(scanner);

        // Get and validate age
        int age = getValidAge(scanner);

        // Get and validate email
        String email = getValidEmail(scanner);

        // Get and validate phone number
        String phone = getValidPhone(scanner);

        // Display the registration information
        System.out.println("\nRegistration Successful!");
        System.out.println("Username: " + username);
        System.out.println("Age: " + age);
        System.out.println("Email: " + email);
        System.out.println("Phone: " + phone);

        scanner.close();
    }

    private static String getValidUsername(Scanner scanner) {
        String username;
        boolean validUsername = false;
        Pattern pattern = Pattern.compile(USERNAME_PATTERN);

        do {
            System.out.print("Enter username (3-15 alphanumeric characters or underscore): ");
            username = scanner.nextLine().trim();

            Matcher matcher = pattern.matcher(username);
            if (!matcher.matches()) {
                System.out.println("Error: Username must be 3-15 characters long and contain only letters, numbers, or underscores.");
            } else {
                validUsername = true;
            }
        } while (!validUsername);

        return username;
    }

    private static int getValidAge(Scanner scanner) {
        int age = 0;
        boolean validAge = false;

        while (!validAge) {
            try {
                System.out.print("Enter your age (0-120): ");
                age = Integer.parseInt(scanner.nextLine());

                if (age < 0 || age > 120) {
                    System.out.println("Error: Age must be between 0 and 120.");
                } else {
                    validAge = true;
                }
            } catch (NumberFormatException e) {
                System.out.println("Error: Please enter a valid numeric age.");
            }
        }

        return age;
    }

    private static String getValidEmail(Scanner scanner) {
        String email;
        boolean validEmail = false;
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);

        do {
            System.out.print("Enter your email: ");
            email = scanner.nextLine().trim();

            Matcher matcher = pattern.matcher(email);
            if (!matcher.matches()) {
                System.out.println("Error: Please enter a valid email address.");
            } else {
                validEmail = true;
            }
        } while (!validEmail);

        return email;
    }

    private static String getValidPhone(Scanner scanner) {
        String phone;
        boolean validPhone = false;
        Pattern pattern = Pattern.compile(PHONE_PATTERN);

        do {
            System.out.print("Enter your phone number (format: 123-456-7890): ");
            phone = scanner.nextLine().trim();

            Matcher matcher = pattern.matcher(phone);
            if (!matcher.matches()) {
                System.out.println("Error: Please enter a valid phone number in the format 123-456-7890.");
            } else {
                validPhone = true;
            }
        } while (!validPhone);

        return phone;
    }
}
  1. Save the file by pressing Ctrl+S.

  2. Compile the program:

javac UserRegistration.java
  1. Run the program:
java UserRegistration
  1. Test the program with different inputs:

    • Try entering an invalid username (too short, containing special characters):
    Enter username (3-15 alphanumeric characters or underscore): a$
    Error: Username must be 3-15 characters long and contain only letters, numbers, or underscores.
    Enter username (3-15 alphanumeric characters or underscore):
    • Try entering an invalid email (missing @ or domain):
    Enter username (3-15 alphanumeric characters or underscore): johndoe
    Enter your age (0-120): 25
    Enter your email: johndoe.com
    Error: Please enter a valid email address.
    Enter your email:
    • Try entering an invalid phone number (wrong format):
    Enter username (3-15 alphanumeric characters or underscore): johndoe
    Enter your age (0-120): 25
    Enter your email: [email protected]
    Enter your phone number (format: 123-456-7890): 1234567890
    Error: Please enter a valid phone number in the format 123-456-7890.
    Enter your phone number (format: 123-456-7890):
    • Enter all valid inputs:
    Enter username (3-15 alphanumeric characters or underscore): johndoe
    Enter your age (0-120): 25
    Enter your email: [email protected]
    Enter your phone number (format: 123-456-7890): 123-456-7890
    
    Registration Successful!
    Username: johndoe
    Age: 25
    Email: [email protected]
    Phone: 123-456-7890

Understanding the Regular Expression Patterns

Let's examine the regular expression patterns used in our program:

  1. USERNAME_PATTERN: ^[a-zA-Z0-9_]{3,15}$

    • ^ and $ ensure that the pattern matches the entire string
    • [a-zA-Z0-9_] matches any letter (upper or lowercase), number, or underscore
    • {3,15} specifies that the length should be between 3 and 15 characters
  2. EMAIL_PATTERN: ^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$

    • This pattern validates email addresses according to common rules
    • It ensures that the email has a username part, an @ symbol, and a domain
  3. PHONE_PATTERN: ^\\d{3}-\\d{3}-\\d{4}$

    • \\d matches any digit (0-9)
    • {3} and {4} specify the number of digits
    • - matches the literal hyphen character

Regular expressions are a powerful tool for input validation, but they can be complex. As you become more comfortable with them, you can create more sophisticated validation patterns for your applications.

Creating a Complete Form Validation System

In this final step, we will build a complete form validation system that incorporates all the techniques we've learned. We'll create a more modular, reusable validation system that can be easily extended for different applications.

Creating a Validation Utility Class

Let's start by creating a utility class that encapsulates our validation methods:

  1. Create a new file named InputValidator.java in the WebIDE.

  2. Add the following code to the file:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * Utility class for validating user input
 */
public class InputValidator {
    // Regular expression patterns
    private static final String USERNAME_PATTERN = "^[a-zA-Z0-9_]{3,15}$";
    private static final String EMAIL_PATTERN = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    private static final String PHONE_PATTERN = "^\\d{3}-\\d{3}-\\d{4}$";
    private static final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$";

    /**
     * Validates a username
     * @param username The username to validate
     * @return true if the username is valid, false otherwise
     */
    public static boolean isValidUsername(String username) {
        if (username == null) {
            return false;
        }
        Pattern pattern = Pattern.compile(USERNAME_PATTERN);
        Matcher matcher = pattern.matcher(username);
        return matcher.matches();
    }

    /**
     * Validates an email address
     * @param email The email to validate
     * @return true if the email is valid, false otherwise
     */
    public static boolean isValidEmail(String email) {
        if (email == null) {
            return false;
        }
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    /**
     * Validates a phone number
     * @param phone The phone number to validate
     * @return true if the phone number is valid, false otherwise
     */
    public static boolean isValidPhone(String phone) {
        if (phone == null) {
            return false;
        }
        Pattern pattern = Pattern.compile(PHONE_PATTERN);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    /**
     * Validates an age
     * @param age The age to validate
     * @return true if the age is valid, false otherwise
     */
    public static boolean isValidAge(int age) {
        return age >= 0 && age <= 120;
    }

    /**
     * Validates a password
     * @param password The password to validate
     * @return true if the password is valid, false otherwise
     */
    public static boolean isValidPassword(String password) {
        if (password == null) {
            return false;
        }
        Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }

    /**
     * Gets the error message for an invalid username
     * @return The error message
     */
    public static String getUsernameErrorMessage() {
        return "Username must be 3-15 characters long and contain only letters, numbers, or underscores.";
    }

    /**
     * Gets the error message for an invalid email
     * @return The error message
     */
    public static String getEmailErrorMessage() {
        return "Please enter a valid email address.";
    }

    /**
     * Gets the error message for an invalid phone number
     * @return The error message
     */
    public static String getPhoneErrorMessage() {
        return "Please enter a valid phone number in the format 123-456-7890.";
    }

    /**
     * Gets the error message for an invalid age
     * @return The error message
     */
    public static String getAgeErrorMessage() {
        return "Age must be between 0 and 120.";
    }

    /**
     * Gets the error message for an invalid password
     * @return The error message
     */
    public static String getPasswordErrorMessage() {
        return "Password must be at least 8 characters long and contain at least one digit, one lowercase letter, one uppercase letter, one special character, and no whitespace.";
    }
}
  1. Save the file by pressing Ctrl+S.

Creating a Complete Registration Form

Now, let's create a new version of our registration form that uses the InputValidator class:

  1. Create a new file named CompleteRegistrationForm.java in the WebIDE.

  2. Add the following code to the file:

import java.util.Scanner;

public class CompleteRegistrationForm {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Collect and validate user information
        String username = getValidInput(scanner, "Username", InputValidator::isValidUsername, InputValidator.getUsernameErrorMessage());
        int age = getValidAge(scanner);
        String email = getValidInput(scanner, "Email", InputValidator::isValidEmail, InputValidator.getEmailErrorMessage());
        String phone = getValidInput(scanner, "Phone number (format: 123-456-7890)", InputValidator::isValidPhone, InputValidator.getPhoneErrorMessage());
        String password = getValidInput(scanner, "Password", InputValidator::isValidPassword, InputValidator.getPasswordErrorMessage());

        // Display the registration information
        System.out.println("\nRegistration Successful!");
        System.out.println("Username: " + username);
        System.out.println("Age: " + age);
        System.out.println("Email: " + email);
        System.out.println("Phone: " + phone);
        System.out.println("Password: " + maskPassword(password));

        scanner.close();
    }

    /**
     * Generic method to get valid input from the user
     * @param scanner The scanner to read input
     * @param fieldName The name of the field being validated
     * @param validator The validation function
     * @param errorMessage The error message to display
     * @return The validated input
     */
    private static String getValidInput(Scanner scanner, String fieldName, java.util.function.Predicate<String> validator, String errorMessage) {
        String input;
        boolean validInput = false;

        do {
            System.out.print("Enter your " + fieldName + ": ");
            input = scanner.nextLine().trim();

            if (!validator.test(input)) {
                System.out.println("Error: " + errorMessage);
            } else {
                validInput = true;
            }
        } while (!validInput);

        return input;
    }

    /**
     * Gets a valid age from the user
     * @param scanner The scanner to read input
     * @return The validated age
     */
    private static int getValidAge(Scanner scanner) {
        int age = 0;
        boolean validAge = false;

        while (!validAge) {
            try {
                System.out.print("Enter your age (0-120): ");
                age = Integer.parseInt(scanner.nextLine());

                if (!InputValidator.isValidAge(age)) {
                    System.out.println("Error: " + InputValidator.getAgeErrorMessage());
                } else {
                    validAge = true;
                }
            } catch (NumberFormatException e) {
                System.out.println("Error: Please enter a valid numeric age.");
            }
        }

        return age;
    }

    /**
     * Masks a password for display
     * @param password The password to mask
     * @return The masked password
     */
    private static String maskPassword(String password) {
        if (password == null || password.isEmpty()) {
            return "";
        }
        return "*".repeat(password.length());
    }
}
  1. Save the file by pressing Ctrl+S.

  2. Compile both Java files:

javac InputValidator.java
javac CompleteRegistrationForm.java
  1. Run the registration form program:
java CompleteRegistrationForm
  1. Follow the prompts to enter valid information for each field. The program will validate each input according to the rules defined in the InputValidator class.

Sample interaction:

Enter your Username: john_doe
Enter your age (0-120): 35
Enter your Email: [email protected]
Enter your Phone number (format: 123-456-7890): 123-456-7890
Enter your Password: weakpw
Error: Password must be at least 8 characters long and contain at least one digit, one lowercase letter, one uppercase letter, one special character, and no whitespace.
Enter your Password: P@ssw0rd123

Registration Successful!
Username: john_doe
Age: 35
Email: [email protected]
Phone: 123-456-7890
Password: ***********

Benefits of This Approach

The approach we've taken in this final example offers several advantages:

  1. Modularity: The validation logic is separated into a reusable utility class.
  2. Extensibility: New validation rules can be easily added to the InputValidator class.
  3. Maintainability: Error messages are centralized and can be easily updated.
  4. Code Reuse: The getValidInput method is generic and can be used for different types of input.
  5. Security: The password is masked when displayed to the user.

This design follows good software engineering principles and makes it easy to adapt the validation system for different applications.

Summary

In this lab, you have learned how to effectively handle invalid user input in Java programs. You have progressed from a basic understanding of input handling to implementing a comprehensive validation system. Here's a summary of what you've accomplished:

  1. Created a basic Java program that collects user input using the Scanner class
  2. Implemented exception handling to gracefully manage invalid input
  3. Added conditional validation to ensure input meets specific criteria
  4. Used regular expressions for advanced pattern-based validation
  5. Built a modular and reusable validation system with a utility class

These techniques are essential for developing robust Java applications that can handle the unpredictable nature of user input. By properly validating and handling invalid input, you can prevent program crashes, maintain data integrity, and provide a better user experience.

As you continue your Java programming journey, remember that input validation is not just about preventing errors but also about enhancing security and usability. The principles you've learned in this lab can be applied to various types of applications, from simple console programs to complex web applications.