Without using BufferedReader Students are often asked to wri

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

Solution

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

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 t
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 t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site