Java Reference
In-Depth Information
being used to read a value of type double , so you can use hasNextDouble to test
whether there is such a value to read:
1 // Reads an input file of numbers and prints the numbers and
2 // their sum.
3
4 import java.io.*;
5 import java.util.*;
6
7 public class ShowSum2 {
8 public static void main(String[] args)
9 throws FileNotFoundException {
10 Scanner input = new Scanner( new File("numbers.dat"));
11
12 double sum = 0.0;
13 int count = 0;
14 while (input.hasNextDouble()) {
15
double next = input.nextDouble();
16
count++;
17
System.out.println("number " + count + " = " + next);
18
sum += next;
19 }
20 System.out.println("Sum = " + sum);
21 }
22 }
This program would work on an input file with any number of numbers;
numbers.dat happens to contain eight. This version of 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
number 6 = 4.7
number 7 = -15.4
number 8 = 2.8
Sum = 329.29999999999995
Structure of Files and Consuming Input
We think of text as being two-dimensional, like a sheet of paper, but from the com-
puter's point of view, each file is just a one-dimensional sequence of characters. For
example, consider the file numbers.dat that we used in the previous section:
 
Search WWH ::




Custom Search