java / beginner
Snippet
Reading User Input with Scanner
The Scanner class is used to read input from various sources, such as the system console. It allows your program to interact with the user by receiving text or numbers.
snippet.java
1
2
3
4
java.util.Scanner scanner = new java.util.Scanner(System.in);System.out.print("Enter your name: ");String name = scanner.nextLine();System.out.println("Hello, " + name);
Breakdown
1
new java.util.Scanner(System.in)
Creates a new Scanner object that reads from the standard input stream (keyboard).
2
scanner.nextLine()
Waits for the user to type text and press Enter, then returns the entire line as a String.