Command Palette

Search for a command to run...

Back to the lesson: Topic 1.13 — Reading Keyboard Input with Scanner
Core Java · Example 4 of 5

Skip bad tokens, and fix the locale

java.util.Scanner reads text from the keyboard (or from a String or file) and splits it into tokens separated by whitespace, converting each one with nextInt, nextDouble, next or nextLine. Check with hasNextInt before you read, and watch out for the leftover line break after nextInt.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Using new Scanner("7 3"), read two integers and print their sum, difference, product and integer quotient on separate labelled lines.

02

Using new Scanner("Meera\n14\n"), read a name with nextLine() and an age, and print Meera will be 18 in 4 years. Read the age the robust way (whole line plus parseInt).

03

Using new Scanner("5 -2 abc 9 0 4.5 3"), add up only the valid integers and print how many tokens were skipped.

Explain it without notes

01

What is a token, and how does nextInt() decide where one ends?

02

Explain why nextLine() after nextInt() returns an empty String, and give two fixes.

03

What is the difference between hasNextInt() and nextInt(), and why does a retry loop need next()?

04

Why should a program create only one Scanner for System.in, and why not close it?

Skip bad tokens, and fix the locale
Sign in to run this example in your browser.

Expected output

number:  12
skipped: abc
number:  7
skipped: x9
number:  30
US double: 1.45
US int:    1000
DE double: 1.45