In Java, the Scanner class is commonly used for reading user input, but there are other methods available that do not require this class. This article will explore how to take input from users using the BufferedReader and Console classes, along with code examples and expected outputs.
BufferedReader in Java
The BufferedReader class can be used to read text from an input stream, which is useful for reading user input from the console.
Here’s how you can use it:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class UserInputBufferedReader {
public static void main(String[] args) {
// Create a BufferedReader object
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
// Prompt the user for input
System.out.print("Enter your name: ");
String name = reader.readLine(); // Read user input
System.out.print("Enter your age: ");
String ageString = reader.readLine(); // Read user input
int age = Integer.parseInt(ageString); // Convert string to integer
// Output the collected inputs
System.out.println("Hello, " + name + "! You are " + age + " years old.");
} catch (IOException e) {
System.out.println("An error occurred while reading input.");
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number for age.");
}
}
}
Explanation
- Imports: The program imports BufferedReader, IOException, and InputStreamReader.
- Creating BufferedReader: A BufferedReader object is created to read input from System.in.
- Reading Input: The program prompts the user for their name and age, reading the input using readLine().
- Error Handling: It includes error handling for IO exceptions and number format exceptions.
Output
When you run this program, it will prompt you for your name and age: