go to previous page   go to home page   go to next page highlighting

Answer:

When "oops" is encountered hasNextInt() returns false and the program ends.

C:\temp>java ManySquares
The square of 1 is 1
The square of 6 is 36
The square of 3 is 9

This might be unfortunate since the program give no indication that there was a problem with the data.


Typical Data

The loop is a sentinel controlled loop. The sentinel is the end of file or something that can't be read as an integer. The following could be the contents of the input file:

1 2 3

10
11
12 13 23 45
67

The input characters form a stream, and several integers, or none, can be on a line. A "line" is nothing more that a sequence of characters in the stream separated by end-of-line characters. A Scanner is perfectly happy to stop in the middle of a line if it has scanned what was expected.

It is tempting to think that the program works only with one integer per line and that each time nextInt() runs that it eats one line. But this is not so.

For this input, the program will write the following lines to the monitor:

The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 10 is 100
The square of 11 is 121
The square of 12 is 144
The square of 13 is 169
The square of 23 is 529
The square of 45 is 2025
The square of 67 is 4489

QUESTION 8:

Would it work if the input file contained the following?

10 12
13 4 6 0
-2
rats

go to previous page   go to home page   go to next page