188k views
5 votes
Write a program that asks the user for the name of a file. The program should display the number of words that the file contains. The file to test your program on is attached to the assignment folder. It is called Lorem.txt.

User Impiyush
by
6.5k points

1 Answer

6 votes

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);

}

}

}

User Primroot
by
6.1k points