Java Reference
In-Depth Information
Display 10.4
Checking for the End of a Text File with
hasNextLine
(part 2 of 2)
File numbered.txt
(after the program is run)
1 Little Miss Muffet
2 sat on a tuffet
3 eating her curves away.
4 Along came a spider
5 who sat down beside her
6 and said "Will you marry me?"
Display 10.5
Checking for the End of a Text File with
hasNextInt
1
import
java.util.Scanner;
2
import
java.io.FileInputStream;
3
import
java.io.FileNotFoundException;
4
public class
HasNextIntDemo
5 {
6
public static void
main(String[] args)
7 {
8 Scanner inputStream =
null
;
9
try
10 {
11 inputStream =
12
new
Scanner(
new
FileInputStream("data.txt"));
13 }
14
catch
(FileNotFoundException e)
15 {
16 System.out.println("File data.txt was not found");
17 System.out.println("or could not be opened.");
18 System.exit(0);
19 }
20
int
next, sum = 0;
21
while
(inputStream.hasNextInt( ))
22 {
23 next = inputStream.nextInt( );
24 sum = sum + next;
25 }
26 inputStream.close( );
27 System.out.println("The sum of the numbers is " + sum);
28 }
29 }
Reading ends when either the end of the file is
reached or a token that is not an
int
is reached.
So, the
5
is never read.
File data.txt
1 2
3 4 hi 5
Screen Output
The sum of the numbers is 10