Friday, November 27, 2009

Chapter 15 Exercise 5

import java.io.*;
import java.util.*;

public class WordsInFile{
public static void main(String[] args){
Scanner stdIn = new Scanner(System.in);
Scanner fileIn;
String word;
int numWords = 0;

try{
System.out.print("Enter a filename: ");
fileIn = new Scanner(new FileReader(stdIn.nextLine()));
while(fileIn.hasNext()){
word = fileIn.next();
numWords++;
}
System.out.print("Number of words = " + numWords + "\n");
fileIn.close();
}
catch(FileNotFoundException e){
System.out.println("Invalid filename.");
}
catch(Exception e){
System.out.println("Error reading from the file.");
}
}//end of main
}//end of WordsInFile class

No comments:

Post a Comment