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.

Respuesta :

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

       }

   }

}