Java Reference
In-Depth Information
You can create such a file with an editor like Notepad on a Windows machine or
TextEdit on a Macintosh. Then you might write a program that processes this input
file and produces some kind of report. For example, the following program reads the
first five numbers from the file and reports their sum:
1 // Program that reads five numbers and reports their sum.
2
3
import
java.io.*;
4
import
java.util.*;
5
6
public class
ShowSum1 {
7
public static void
main(String[] args)
8
throws
FileNotFoundException {
9 Scanner input =
new
Scanner(
new
File("numbers.dat"));
10
11
double
sum = 0.0;
12
for
(
int
i = 1; i <= 5; i++) {
13
double
next = input.nextDouble();
14 System.out.println("number " + i + " = " + next);
15 sum += next;
16 }
17 System.out.println("Sum = " + sum);
18 }
19 }
This program uses a variation of the cumulative sum code from Chapter 4.
Remember that you need a
throws
clause in the header for
main
because there is a
potential
FileNotFoundException
. The program produces the following output:
number 1 = 308.2
number 2 = 14.9
number 3 = 7.4
number 4 = 2.8
number 5 = 3.9
Sum = 337.19999999999993
Notice that the reported sum is not 337.2. This result is another example of a
roundoff error (also described in Chapter 4).
The preceding program reads exactly five numbers from the file. More typically,
you'll continue to read numbers as long as there are more numbers to read while a
while
loop is executing. Remember that the
Scanner
class includes a series of
hasNext
methods that parallel the various
next
methods. In this case,
nextDouble
is
Search WWH ::
Custom Search