Java Reference
In-Depth Information
The user also has the option of specifying a full file path:
This program will add a series
of numbers from a file.
What is the file name? C:\data\numbers.dat
number 1 = 308.2
number 2 = 14.9
number 3 = 7.4
number 4 = 2.8
number 5 = 3.9
number 6 = 4.7
number 7 = -15.4
number 8 = 2.8
Sum = 329.29999999999995
Notice that the user doesn't have to type two backslashes to get a single backslash.
The Scanner object that reads the user's input is able to read it without escape
sequences.
A More Complex Input File
Suppose an input file contains information about how many hours each employee of
a company has worked. It might look like the following:
Erica 7.5 8.5 10.25 8 8.5
Erin 10.5 11.5 12 11 10.75
Simone 8 8 8
Ryan 6.5 8 9.25 8
Kendall 2.5 3
Suppose you want to find out the total number of hours worked by each individual.
You can construct a Scanner object linked to this file to solve this task. As you start
writing more complex file-processing programs, you will want to divide the program
into methods to break up the code into logical subtasks. In this case, you can open the
file in main and write a separate method to process the file.
Most file processing will involve while loops, because you won't know in
advance how much data the file contains. You'll need to write different tests, depend-
ing on the particular file being processed, but they will almost all be calls on the vari-
ous hasNext methods of the Scanner class. You basically want to say, “While you
have more data for me to process, let's keep reading.”
In this case, the data is a series of input lines that each begins with a name. For
this program you can assume that names are simple, with no spaces in the middle.
 
Search WWH ::




Custom Search