To get user input in Java, you can use the Scanner
class, which is available in the java.util
package. Here's a simple example of how you can use it to read user input from the console:
import java.util.Scanner; public class UserInputExample { public static void main(String[] args) { // Create a Scanner object Scanner scanner = new Scanner(System.in); // Prompt the user to enter their name System.out.print("Enter your name: "); // Read the input provided by the user String name = scanner.nextLine(); // Display a greeting message System.out.println("Hello, " + name + "!"); // Close the Scanner to release resources scanner.close(); } }
In this example, scanner.nextLine()
is used to read a line of text input from the user. You can use other methods like nextInt()
, nextDouble()
, etc., to read different types of input.