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

Without using BufferedReader** Students are often asked to write term papers con

ID: 3924223 • Letter: W

Question

Without using BufferedReader**

Students are often asked to write term papers containing a certain number of words. Counting words in a long paper is a tedious task, but the computer can help. Write a program that counts the number of words, lines, and total characters (not including whitespace) in a paper, assuming that consecutive words are separated either by spaces or end-of-line characters. Your program should be named WordCount.java. For example, the follow file:

Students are often asked to write term papers containing a certain number of words. Counting words in a long paper is a tedious task, but the computer can help. Write a program that counts the number of words, lines, and total characters (not including whitespace) in a paper, assuming that consecutive words are separated either by spaces or end-of-line characters. Your program should be named WordCount.java. should result in the following output:

Total lines = 5

Total words = 66

Total chars = 346

Explanation / Answer

WordCount.java

import java.io.File;
import java.io.IOException;
import java.util.Scanner;


public class WordCount {

  
   public static void main(String[] args) throws IOException {
           File file = new File("words.txt");
           if(file.exists()){
               Scanner scan = new Scanner(file);
               int wordCount = 0;
               int totalChar = 0;
               int lineCount = 0;
               String sCurrentLine;
               while (scan.hasNextLine()) {
                   sCurrentLine = scan.nextLine();
                   lineCount++;
                   String words[] = sCurrentLine.split("\s+");
                   wordCount = wordCount + words.length;
                   for(int i=0; i<words.length; i++){
                       totalChar = totalChar + words[i].length();
                   }
               }
               System.out.println("Total lines = "+lineCount);
               System.out.println("Total words = "+wordCount);
               System.out.println("Total chars = "+totalChar);
           }
           else{
               System.out.println("File does not exist.");
           }

   }

}

Output:

Total lines = 5
Total words = 66
Total chars = 346

Words.txt

cat intolerable dog
intolerable elephat
curd intolerable
daft cat elephat
dog

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote