EMZETT.
Login

User Input

In short: Accepting input from the console — in Java usually via the Scanner class from java.util.

In more detail: Scanner reads from System.in and offers typed methods like nextInt(), nextDouble(), or nextLine(). A common pitfall: calling nextLine() directly after nextInt() returns an empty string, because nextInt() doesn’t consume the line break after the number.

Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();

In Depth

Scanner scanner = new Scanner(System.in);
 
System.out.print("What's your name? ");
String name = scanner.nextLine(); // reads a whole line
 
System.out.print("How old are you? ");
int age = scanner.nextInt();    // only reads up to the next whitespace/line break
scanner.nextLine();               // consumes the leftover line break after nextInt()
 
System.out.print("What's your city? ");
String city = scanner.nextLine(); // would otherwise be empty!
 
scanner.close(); // best practice, usually not strictly necessary for System.in

The classic Scanner pitfall: methods like nextInt(), nextDouble(), or nextBoolean() ONLY read the actual value up to the next whitespace, but leave the trailing line break (Enter key) behind in the input buffer. If you call nextLine() directly afterwards, it immediately reads the leftover, empty rest of the current line instead of the next real input — which is why an nextInt()/nextDouble()/etc. usually needs an additional, “consuming” nextLine() call afterwards, before you want to read a whole line of text again.

A second common problem: nextInt() throws an InputMismatchException if the input isn’t a valid number (e.g. letters instead of digits) — with no exception handling, the program then simply crashes. Robust code therefore checks beforehand with scanner.hasNextInt() whether a valid integer is even coming up next, instead of blindly calling nextInt() and crashing on error.

See also: do-while Loop, Errors