4 min read
Reading User Input
Prerequisites: String formatting
Scanner reads input typed by the person running the program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What's your name? ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
Common mistakes
- Mixing
nextInt()withnextLine()—nextInt()doesn't consume the newline character left behind, so a followingnextLine()call can appear to be skipped. Callscanner.nextLine()once extra to consume it, or usenextLine()everywhere and parse manually.