W3docs

Getting Keyboard Input

To get keyboard input in Java, you can use the Scanner class from the java.util package.

To get keyboard input in Java, you can use the Scanner class from the java.util package. The Scanner class provides methods for reading input from the keyboard and parsing it into different data types (such as int, double, etc.).

Here is an example of how you can use the Scanner class to get keyboard input in Java:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            System.out.print("Enter a number: ");
            if (input.hasNextInt()) {
                int num = input.nextInt();
                System.out.println("You entered: " + num);
            } else {
                System.out.println("Invalid input. Please enter an integer.");
            }
        }
    }
}

In this example, the Scanner class is used to read an integer from the keyboard. The hasNextInt() method checks if the next token is an integer before calling nextInt(), which prevents InputMismatchException. The try-with-resources block automatically closes the Scanner when the block exits, following modern Java best practices.

You can also use the nextLine() method to read a whole line of input as a string.

For example:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            System.out.print("Enter a line of text: ");
            String line = input.nextLine();
            System.out.println("You entered: " + line);
        }
    }
}

This code reads a whole line of text from the keyboard and stores it in the line variable.

Keep in mind that the Scanner class reads input in a blocking manner, which means that the program will wait for the user to enter input before continuing.

I hope this helps! Let me know if you have any other questions.