Answer:
import java.io.*;
import java.util.Scanner;
public class CountWordsInFile {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter file name: ");
String fileName = keyboard.next();
File file = new File(fileName);
try {
Scanner scan = new Scanner(file);
int count = 0;
while(scan.hasNext()) {
scan.next();
count += 1;
}
scan.close();
System.out.println("Number of words: "+count);
} catch (FileNotFoundException e) {
System.out.println("File " + file.getName() + " not present ");
System.exit(0);
}
}
}