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

Java program to use (Reading a File) Method to read a [.txt] file. Some reading

ID: 672711 • Letter: J

Question

Java program to use (Reading a File) Method to read a [.txt] file.

Some reading educators have claimed that you can judge the difficulty of a piece of text by counting the number of letters in a word and the number of words in a sentence. You are to write a program that reads a text file and reports the average number of letters in a word and the average number of words in a sentence. The java.util.Scanner next () method will read a single English word from a text file. You can use this method to read individual words. For the purpose of this assignment, we will consider sentences to be a number of words that end with a period. The last word of a sentence (when read with the next () method) will end with a period or an exclamation point(!). The String method endsWith (" . ") will return a boolean value that is true if the word ends with a period. Your program should first ask the user the name of the input file. It should then use that name to create a java.io.File object and a java.util.Scanner object. The String length () method can be used to get the number of letters in a word. Don't forget to subtract one from the length if the word ends in a period. The program is not completely accurate because it misses sentences that end with a "quote." It also misses sentences that end is a question mark. You can modify your program to look for words that end in any of the following letters.

Explanation / Answer

import java.util.*;
import java.io.*;

public class countWord
{

   public static void main(String[] args) {
   try
   {

       Scanner input = new Scanner(new FileReader("data.txt"));
  

       PrintWriter output = new PrintWriter(new FileOutputStream("newfile.txt"));

       int lineNum = 0;
       int wordCount = 1;
       int charCount = 0;

       while (input.hasNextLine())
       {
           String line;
           line = input.nextLine();

           lineNum++;

           String str [] = line.split((" "));
           for ( int i = 0; i <str.length ; i ++)
           {
               if (str [i].length() > 0)
               {
                   wordCount ++;
               }
           }
           charCount += (line.length());

       }

       System.out.println(lineNum);
       System.out.println(wordCount);
       System.out.println(charCount);
       input.close();
       output.close();

       System.out.print("File written.");

   }

   catch (FileNotFoundException e)
   {
       System.out.println("error opening one of the files.");
   }
}
}

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