Read numbers until the input ends
while loops are covered in Topic 2.5; here it just repeats as long as another whole number is waiting.
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.
Using new Scanner("7 3"), read two integers and print their sum, difference, product and integer quotient on separate labelled lines.
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).
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
What is a token, and how does nextInt() decide where one ends?
Explain why nextLine() after nextInt() returns an empty String, and give two fixes.
What is the difference between hasNextInt() and nextInt(), and why does a retry loop need next()?
Why should a program create only one Scanner for System.in, and why not close it?
Expected output
count: 4
sum: 100
average: 25.0