BufferedReader

To read user inputs of various data types using the BufferedReader class in Java, you can read lines of text from the console and then parse them into the desired data types. Here's an example of reading user inputs for different data types:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderInputExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        // Read a string
        System.out.print("Enter your name: ");
        String name = reader.readLine();

        // Read an integer
        System.out.print("Enter your age: ");
        int age = Integer.parseInt(reader.readLine());

        // Read a double
        System.out.print("Enter your salary: ");
        double salary = Double.parseDouble(reader.readLine());

        // Read a boolean
        System.out.print("Are you married? (true/false): ");
        boolean isMarried = Boolean.parseBoolean(reader.readLine());

        // Read a character
        System.out.print("Enter a single character: ");
        char singleChar = reader.readLine().charAt(0);

        // Display the inputs
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
        System.out.println("Married: " + isMarried);
        System.out.println("Character: " + singleChar);

        reader.close(); // Close the reader when done
    }
}

In this example:

  • We use readLine() to read lines of text from the console.

  • We parse the lines into different data types using methods like Integer.parseInt(), Double.parseDouble(), Boolean.parseBoolean(), and charAt(0) for a single character.

  • We display the parsed values to confirm that the inputs were successfully converted.

Ensure that you handle exceptions properly, as user input can be unpredictable, and invalid input can lead to exceptions during parsing.

Last updated