Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 02 / Topic 6 of 9

Reading input with Scanner

Scanner reads text the user types from System.in (the keyboard). It lives in java.util, so it needs an import line at the top of the file.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

System.out.print("How many people are at the table? ");
int people = scanner.nextInt();

System.out.print("Enter the bill amount: ");
double amount = scanner.nextDouble();

scanner.nextLine();   // see the warning below

System.out.print("Enter your name: ");
String name = scanner.nextLine();

Real transcript — what you see in the terminal, prompt and typed answer together (examples/05_scanner_input.java):

How many people are at the table? 4
Enter the bill amount: 1200.50
Enter your name: Asha Kulkarni
---
Name     : Asha Kulkarni
People   : 4
Amount   : 1200.5
Per head : 300.125
Method Reads Stops at
nextInt() an int whitespace (space, tab, Enter)
nextDouble() a double whitespace
nextLine() a full line of text the Enter key

The classic Scanner trap: nextInt() and nextDouble() read only the number, leaving the Enter key's newline sitting unread in the buffer. If the next call is nextLine(), it reads that leftover newline as an empty line instead of waiting for real input. The fix is an extra, throwaway scanner.nextLine(); right after the last nextInt()/nextDouble() and before the next nextLine(), exactly as shown above.

🔍 Going deeper: if the text typed does not match what the method expects (letters where nextInt() expects digits), Scanner throws InputMismatchException — another crash that Part 6 will teach you to catch. scanner.close() at the end releases the resource; closing System.in does not usually matter for a short CLI program, but it is good habit.

Full program: examples/05_scanner_input.java.

Done here? The practice set for Part 2 — including the solutions — is on the part page.

Search the guide