Approaches to provide dynamic input in Java

  1. BufferedReader Class with InputStreamReader Class
  2. Scanner Class
  3. Console class
  4. Command Line Arguments

BufferedReader Class with InputStreamReader Class

BufferedReader Class with InputStreamReader Class

The BufferedReader and InputStreamReader classes are essential in Java for handling input from various sources, such as the command line, files, or network streams. When used together, they provide an efficient way to read text-based input while optimizing performance.

Problem: Command-line Input for a User Profile

We will create a program that:

  1. Reads user inputs (name, age, and email).
  2. Validates the inputs (for example, age must be a number and email must contain "@" and ".").
  3. Displays the user's profile if the input is valid.
Code Example
Output
Scenario 1: Valid Input

Enter your name: Alice
Enter your age: 25
Enter your email: alice@example.com

User Profile:
Name: Alice
Age: 25
Email: alice@example.com

Explanation:

  1. BufferedReader and InputStreamReader:
    • We use BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); to chain these two classes, allowing for efficient and easy reading of character input from the console.
    • System.in is the InputStream connected to the console, and InputStreamReader converts this byte-based stream into character-based data. BufferedReader adds efficiency with its buffer and provides the readLine() method to read whole lines of input.
  2. Input and Validation:
    • The program first asks the user for their name. If the input is empty, the program displays an error and exits.
    • Then, the user is prompted for their age, which must be a valid number. If it's not, a NumberFormatException is caught, and the user is informed that the input is invalid.
    • Finally, the email input is validated by checking whether it contains both an "@" and a "." using the isValidEmail() helper function.
  3. Displaying Profile:
    • Once all inputs are validated, the program displays the user profile: name, age, and email.