Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

6.1 Scanner — reading numbers and words

Lesson

You already use this

Since module 2 every practice task began with two lines you were told to treat as a recipe:

Scanner in = new Scanner(System.in);
int n = in.nextInt();

Now you know enough to see what they really are. Scanner is a class from Java's library — that is why the file needs import java.util.Scanner; at the top. new Scanner(System.in) builds an object of that class, wired to the keyboard input, exactly like the objects you built in module 4. And in.nextInt() is an instance method call on that object.

This lesson goes further: reading words as well as numbers, reading whole lines, and reading from a file instead of the keyboard.


Reading values one at a time

A Scanner reads a stream of values, one at a time. nextInt() reads the next whole number, nextDouble() reads a decimal, next() reads one word, and nextBoolean() reads a boolean. Each of these has a matching hasNextInt(), hasNextDouble(), and so on, that reports whether another value of that type is waiting. Always check the hasNext… method before calling the next… method — otherwise reading past the end causes an error.


Worked example

Scanner sc = new Scanner(System.in);
int sum = 0;
while (sc.hasNextInt()) {   // is there another int to read?
    sum = sum + sc.nextInt();
}
System.out.println("Sum: " + sum);

The loop reads integers until there are no more, adding each to sum. For the input 3 5 7 2 it prints Sum: 17.


▶ Try it: run this, type a few whole numbers separated by spaces into the input box, and see their total. Change the numbers and re-run.



Which method reads the next whole number from a Scanner?


Before calling nextInt(), you should check...


Type exactly what this program prints for the input shown.

Scanner sc = new Scanner(System.in);
int sum = 0;
while (sc.hasNextInt()) {
    sum = sum + sc.nextInt();
}
System.out.println("Sum: " + sum);

Input: 4 5 6


Match each Scanner method to what it reads.


True or false?