Console

In Java, you can read user inputs of various data types using the System.console() method along with the readLine() method for string inputs and then parse or convert them to the desired data types. Here's how you can read user inputs of different data types with System.console():

public class ConsoleInputExample {
    public static void main(String[] args) {
        // Obtain a console object
        Console console = System.console();

        if (console == null) {
            System.out.println("Console is not available. Please run this program from the command line.");
            System.exit(1);
        }

        // Read a string input
        String name = console.readLine("Enter your name: ");

        // Read an integer input
        int age = Integer.parseInt(console.readLine("Enter your age: "));

        // Read a double input
        double salary = Double.parseDouble(console.readLine("Enter your salary: "));

        // Read a boolean input
        boolean isStudent = Boolean.parseBoolean(console.readLine("Are you a student? (true/false): "));

        // Print the inputs
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
        System.out.println("Is Student: " + isStudent);
    }
}

In this example:

  1. We first obtain a Console object using System.console(). Note that System.console() might return null if it's not available, for example, when running in an IDE.

  2. We read string input using console.readLine(). For other data types, we read strings and then parse them into the appropriate data type using methods like Integer.parseInt() and Double.parseDouble().

  3. We demonstrate reading integer, double, and boolean inputs, but you can use similar parsing techniques for other data types.

  4. Finally, we print the values of the user inputs.

Remember to handle exceptions when parsing the input strings into other data types to ensure your program doesn't crash if the user enters invalid input.

Last updated