Java Reference
In-Depth Information
Here's how to modify the header for the
main
method to include a
throws
clause
indicating that it may throw a
FileNotFoundException
:
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("hamlet.txt"));
...
}
With the
throws
clause, the line becomes so long that we have to break it into two
lines to allow it to fit in the margins of the textbook. On your own computer, you will
probably include all of it on a single line.
After this modification, the program compiles. Once you've constructed the
Scanner
so that it reads from the file, you can manipulate it like any other
Scanner
. Of course,
you should always prompt before reading from the console to give the user an indication
of what kind of data you want, but when reading from a file, you don't need to prompt
because the data is already there, stored in the file. For example, you could write a pro-
gram like the following to count the number of words in
Hamlet
:
1 // Counts the number of words in Hamlet.
2
3
import
java.io.*;
4
import
java.util.*;
5
6
public class
CountWords {
7
public static void
main(String[] args)
8
throws
FileNotFoundException {
9 Scanner input =
new
Scanner(
new
File("hamlet.txt"));
10
int
count = 0;
11
while
(input.hasNext()) {
12
String word = input.next();
13
count++;
14 }
15 System.out.println("total words = " + count);
16 }
17 }
Note that you have to include an import from
java.util
for the
Scanner
class
and an import from
java.io
for the
File
class. The program generates the follow-
ing output:
total words = 31956
Search WWH ::
Custom Search