Module 2 · Java Basics — topic 4 of 5
Input with Scanner and Formatted Output
Reading numbers, words and whole lines from the keyboard with Scanner, avoiding the nextInt/nextLine trap, validating input, and formatting output.
Learning objectives
- Read numbers, words and lines with Scanner
- Explain and fix the leftover-newline problem after nextInt
- Validate input with hasNextInt before reading
Definition
java.util.Scanner reads and parses text from an input source such as System.in, splitting it into tokens separated by whitespace and converting them with methods like nextInt, nextDouble and nextLine.
Introduction
Interactive programs need to ask the user for data. The easiest tool in Java is Scanner, which wraps the standard input stream and turns typed text into numbers and strings. It is used in nearly every beginner program and in every interactive project in this course.
Why it matters
Most beginner bugs with input come from mixing nextInt() and nextLine(); understanding tokens fixes them for good.
Programs that validate input don't crash when someone types abc instead of a number.
Detailed explanation
Create one Scanner for the whole program: Scanner in = new Scanner(System.in);. Creating several on System.in can lose buffered input.
Token methods — next(), nextInt(), nextDouble(), nextBoolean() — skip whitespace, read one token and convert it. If the token isn't of the right type they throw InputMismatchException and leave the token unread.
nextLine() reads everything up to the end of the current line and consumes the newline. Because token methods stop *before* the newline, calling nextLine() right after nextInt() returns an empty string — the rest of the number's line. Fix it by calling in.nextLine() once to discard the remainder, or read every line with nextLine() and parse it yourself.
hasNext methods — hasNextInt(), hasNextLine() and so on — look ahead without consuming anything. Use them to validate input or to read until the input ends (end of file is Ctrl+D on Linux/macOS, Ctrl+Z then Enter on Windows).
Output. System.out.printf and String.format use the same format specifiers: width, precision and flags such as %-10s, %8.2f, %,d (thousands separators) and %05d (zero padding).
For large inputs, BufferedReader with readLine() is faster than Scanner; competitive programmers often use it. Scanner's convenience is perfect for interactive programs.
Syntax
next()reads one word;nextLine()reads the whole line.- Check
hasNextInt()beforenextInt()to avoid exceptions. - Don't close a Scanner on System.in until the program no longer needs input.
Code examples
Reading two numbers
12 30
Enter two numbers: 12 + 30 = 42
The println after reading starts a fresh line, because typed input isn't part of the program's output.
The nextInt / nextLine trap
20 Asha Rao
age=20, rest='', name='Asha Rao'
More examples
Validating input until the data ends
78 91 abc 64 105 88 -3 x7
skipping 'abc' skipping 'x7' 4 marks, average 80.25, highest 91, rejected 4
Step-by-step explanation
in.hasNext()is true while any token remains, so the loop processes the whole input regardless of how it is split into lines.hasNextInt()checks the next token without consuming it.- Valid integers outside 0–100 are counted as rejected and skipped with
continue. - Non-numeric tokens must be consumed with
in.next(); otherwisehasNextInt()would see the same token forever. - The average casts
sumto double before dividing: (78 + 91 + 64 + 88) / 4 = 80.25.
Expected output
Running “Validating input until the data ends” with the sample input shown prints exactly:
Practical applications
- Menu-driven console applications
- Reading test data in coding contests
- Command-line tools that read piped input until end of file
Best practices
- Create one Scanner per input source and reuse it.
- Validate with hasNextInt/hasNextDouble before reading numbers from users.
- Print a prompt with
print(no newline) so the user types on the same line.
Common mistakes
Reading a line right after a number
Avoid
Prefer
nextInt leaves the newline in the buffer; the next nextLine reads just that newline.
Not consuming an invalid token
Avoid
Prefer
hasNextInt never consumes input, so without in.next() the loop sees the same bad token forever.
Important notes
- Scanner's number parsing follows the default locale; in locales that use a comma as the decimal separator,
nextDouble()expects3,5. Usenew Scanner(System.in).useLocale(java.util.Locale.ROOT)for consistent behaviour. - When input is piped from a file, the typed text doesn't appear in the output — only what the program prints does.
Key takeaways
- Scanner token methods read one whitespace-separated token; nextLine reads the rest of a line.
- Call nextLine once after nextInt before reading a full line.
- Use hasNextInt and in.next() to validate and skip bad input.
Try it yourself
- 1Read a name (full line) and an age, and print a greeting with the age next year.
- 2Read numbers until end of input and print their count, minimum and maximum.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerAfter `int n = in.nextInt();`, why does the next `in.nextLine()` return an empty string?
- BeginnerWhat is printed?