Java Reference
In-Depth Information
To read the
ID
we use the method
nextInt
; to read the name we use the method
nextLine
. Notice that after reading the
ID
, the reading marker is after the
ID
and the
character after the
ID
is the newline character. Therefore, after reading the
ID
, the
reading marker is after the
ID
and at the newline character (of the line containing the
ID
).
The method
nextLine
reads until the end of the line. Therefore, if we read the name
immediately after reading the
ID
, then the method
nextLine
will position the reading
marker after the newline character following the
ID
, and nothing will be stored in the
variable
name
. Because the reading marker is just before the name, if we use the method
nextInt
to read the voting data, the program will terminate with an error message.
Therefore, it follows that to read the name, we must discard the newline character after
the
ID
, which we can do using the method
nextLine
. (Assume that
discard
is a
variable of type
String
.) Therefore, the statements to read the
ID
and name are as
follows:
ID = inFile.nextInt();
//read the ID
discard = inFile.nextLine();
//discard the newline character
//after the ID
name = inFile.nextLine();
//read the name
The general loop to process the data is:
5
while
(inFile.hasNext())
//Line 1
{
//Line 2
ID = inFile.nextInt();
//Line 3
discard = inFile.nextLine();
//Line 4
name = inFile.nextLine();
//Line 5
//process the numbers in each line
}
The code to read and sum up the voting data uses a
while
loop as follows:
sum = 0;
//Line 6
num = inFile.nextInt();
//Line 7; read the first number
while
(num != -999)
//Line 8
{
//Line 9
sum = sum + num;
//Line 10; update sum
num = inFile.nextInt();
//Line 11; read the next number
}
//Line 12
We can now write the following nested loop to process the data:
while
(inFile.hasNext())
//Line 1
{
//Line 2
ID = inFile.nextInt();
//Line 3
discard = inFile.nextLine();
//Line 4
name = inFile.nextLine();
//Line 5
sum = 0;
//Line 6
num = inFile.nextInt();
//Line 7; read the first number
Search WWH ::
Custom Search