Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

6.20: Word Count Write a program that prompts the user to input the name of a te

ID: 3718633 • Letter: 6

Question

6.20: Word Count Write a program that prompts the user to input the name of a text file and then outputs the number of words in the file. You can consider a "word" to be any text that is surrounded by whitespace (for example, a space, carriage return, newline) or borders the beginning or end of the file.

Input Notes:There are two input sources in this program: the text file and standard input. The standard input consists of a single word, the name of the text file to be read. Don't use a string variable.

Output Notes (Prompts and Labels): The filename provided in standard input is prompted for with "Enter a file name: " and displayed so that the filename entered is on the same line as the prompt. The output of the program is a single line of the form: "The file contains N words." where N is the number of words determined by the program.

Explanation / Answer

package Chegg;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.Scanner;

public class WordCount {

//main method

public static void main(String[] args) throws IOException {

Scanner sc = new Scanner(System.in);

System.out.println("Input the name of a text file");

String filename=sc.next();

//Reader file = new File("C:/Users/jajraraj/Desktop/sample.txt");

FileReader fr = new FileReader ("C:/"+filename);   

BufferedReader br = new BufferedReader (fr);

String line = br.readLine();

int count = 0;

while (line != null) {

String []parts = line.split(" ");

for( String w : parts)

{

count++;   

}

line = br.readLine();

}

System.out.println("The file contains "+count+" words.");

}

}

-------------------

output sample:-

Input the name of a text file
sample.txt
The file contains 23 words.

---------------------------------------------------------------------------------------------

If you have any query, please feel free to ask.

Thanks a lot.