Question

Program Behavior Each time your program is run, it will prompt the user to enter the...

Program Behavior

Each time your program is run, it will prompt the user to enter the name of an input file to analyze. It will then read and analyze the contents of the input file, then print the results.

Here is a sample run of the program. User input is shown in red.

Let's analyze some text!
Enter file name: sample.txt
Number of lines: 21
Number of words: 184
Number of long words: 49
Number of sentences: 14
Number of capitalized words: 19

Make sure the output of your program conforms to this sample run. Of course, the values produced will be different depending on the input file being analyzed.

The sample input file that was used for this example can be downloaded from here. You can use it for testing your program, but you should also test it against other input files. To use a file for testing, just add it to the project folder.

The contents of that sample input file are:

This is a sample text file used as input for Project 2. It contains regular
English text in sentences and paragraphs that are analyzed by the program.

The program counts the number of lines in the input file, as well as the
total number of words. It also counts the number of long words in the file.
A word is considered long if it has more than five characters. The program
also counts the number of sentences by counting the number of periods in
the file.

Finally, the program counts the number of capitalized words in the input
file. It uses a separate method to determine if a word is capitalized.

Blank lines will count toward the line count, but do not contribute any
words.

This program uses Scanner objects in three ways. One Scanner object is used
to read the file name that the user types at the keyboard. Another Scanner
is used to read each line in the file, and the third is used to parse the
individual words on the line.

This concludes this sample input file. Have a nice day.

Program Design

Create a new BlueJ project called Project2 and inside that create a class called TextAnalyzer. Add a static method called analyze. which will do most of the process for this program. The header of the method should look like this:

public static void analyze() throws IOException

Notice the addition of the throws keyword. This simply tells the compiler that the code inside the method might cause a run-time error of type IOException. This will happen in the case when you enter a file name that doesn't exist inside the project's folder. Using the throws keyword, you are delegating the responsibility of handling this IO (Input Output) run-time error to the caller of the method so you don't need to handle an error like this in your code.

Use three different Scanner objects to accomplish this program. One will read the name of the input file from the user, another will read each line of the input file, and the third will be used to parse each line into separate words.

Determine the appropriate places in your program to count the following:

  • lines - each line in the input file (terminated by the end-of-line character)
  • words - any text separated by white space
  • long words - any word longer than 5 characters
  • sentences - an English sentence that ends in a period. The last word in a sentence will contain a period (search for the appropriate method to use in the String API (Links to an external site.). )
  • capitalized words - any word that begins with an uppercase alphabetic character

For the purposes of our analysis, a word is defined as any set of continuous characters separated by white space (spaces, tabs, or new line characters). Punctuation will get caught up in the words. For example, in the sample input file "Finally," is a considered a single word, including the comma. Likewise, "2." and "ways." are words.

The sentence count is really just a count of the periods in the input file. Or, more precisely for your program, it is the count of the number of words that contain a period. Notice the difference between counting lines and counting sentences.

You will define a second, separate method to help analyze capitalized words. Write a method called wordIsCapitalizedthat accepts a String parameter representing a single word and returns a boolean result. Return true if the first character of the word is an uppercase alphabetic character and false otherwise. Fortunately, there is a method called isUpperCase already defined in the Character class of the Java API that can help with this.

Developing the Program

As always: work on your solution in stages. Don't try to get the whole thing written before compiling and testing it. Suggestions:

  • Get the infrastructure of the program set up, printing just the intro line and the first prompt. Compile and run the program.
  • Set up the Scanner object for reading the input file name. Read the file name and print it back out temporarily. Compile and test.
  • Now set up the second Scanner object to read from the input file. Write the loop to read each line of the input file and print it back out. Again, this is temporary output just to prove to yourself that you're reading the file correctly. Then you can move forward with confidence that that part is squared away.
  • Then address each part of the analysis one at a time. Set up the variable you need to keep the count, increment it at the right time, and print it out at the end. Compile and test at each step.
  • Finally, write the separate method to test a word for capitalization. Call it where appropriate. Test.
  • Once you've got the program working for the sample input file, make another one and test using it.

Homework Answers

Answer #1

Short Summary:

  • Provided the source code and sample output as per the requirements.
  • Place the input file in the project directory,

**************Please upvote the answer and appreciate our time.************

Source Code:

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

public class TextAnalyzer {

   /**
   * @param word a String parameter representing a single word
   * @return true if the first character of the word is an uppercase alphabetic
   * character and false otherwise
   */
   public static boolean wordIsCapitalized(String word) {
       if (Character.isUpperCase(word.charAt(0))) {
           return true;
       }
       return false;
   }

   public static void analyze() throws IOException {

       // read the name of the input file from the user
       Scanner keyboard = new Scanner(System.in);

       // Get file name from user
       System.out.print("Enter file name: ");
       String fileName = keyboard.nextLine();

       // Declare variable to store
       int linesCount = 0, wordsCount = 0, longWordsCount = 0, sentencesCount = 0, capitalizedWordsCount = 0;
       // read each line of the input file
       // Create an instance of File for input file
       File inputFile = new File(fileName);
       Scanner lineReader = new Scanner(inputFile);
       while (lineReader.hasNextLine()) {
           // Increase the line count
           linesCount++;

           String line = lineReader.nextLine();

           // to parse each line into separate words.
           Scanner parser = new Scanner(line);
           while (parser.hasNext()) {
               // Increase the word count
               wordsCount++;

               // Get each splitted data from the Scanner object
               String word = parser.next();

               // Verify if it long word
               if (word.length() > 5) {
                   longWordsCount++;
               }

               // if it has period, increase sentences count
               if (word.contains(".")) {
                   sentencesCount++;
               }

               // verify if it is capitalized word
               if (wordIsCapitalized(word)) {
                   capitalizedWordsCount++;
               }
           }
       }

       // Print the results
       System.out.println("Number of lines: " + linesCount);
       System.out.println("Number of words: " + wordsCount);
       System.out.println("Number of long words: " + longWordsCount);
       System.out.println("Number of sentences: " + sentencesCount);
       System.out.println("Number of capitalized words: " + capitalizedWordsCount);

   }

   public static void main(String[] args) {
       // TODO Auto-generated method stub
       try {
           analyze();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

   }

}

Refer the following screenshots for code indentation:

Sample Run:

**************************************************************************************

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
You will write a program that loops until the user selects 0 to exit. In the...
You will write a program that loops until the user selects 0 to exit. In the loop the user interactively selects a menu choice to compress or decompress a file. There are three menu options: Option 0: allows the user to exit the program. Option 1: allows the user to compress the specified input file and store the result in an output file. Option 2: allows the user to decompress the specified input file and store the result in an...
Write a C program that prompts the user to enter a line of text on the...
Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr and readLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate on NUL-terminated...
Write an assembly program that reads characters from standard input until the “end of file” is...
Write an assembly program that reads characters from standard input until the “end of file” is reached. The input provided to the program contains A, C, T, and G characters. The file also may have new line characters (ASCII code 10 decimal), which should be skipped/ignored. The program then must print the count for each character. You can assume (in this whole assignment) that the input doe not contain any other kinds of characters.  the X86 assembly program that simply counts...
Write a python program that will perform text analysis on an input text using all of...
Write a python program that will perform text analysis on an input text using all of the following steps: 1. Take the name of an input file as a command line argument. For example, your program might be called using python3 freq.py example1 to direct you to process a plain text file called example. More information is given on how to do this below. 2. Read the contents of the file into your program and divide the text into a...
Create a program that filters the data in a CSV file of product data based on...
Create a program that filters the data in a CSV file of product data based on some search word and prints the resulting output to a new file. Additionally, the program will print the number of items filtered to stdout. • Your program should take three arguments: an input file to process, an output file to save the results, and a search word. • If the output file already exists or cannot be opened, warn the user by printing "CANNOT...
Writing a program in Python that reads a text file and organizes the words in the...
Writing a program in Python that reads a text file and organizes the words in the file into a list without repeating words and in all lowercase. Here is what I have #This program takes a user input file name and returns each word in a list #and how many different words are in the program. while True:   #While loop to loop program     words = 0     #list1 = ['Programmers','add','an','operating','system','and','set','of','applications','to','the','hardware',          # 'we','end','up','with','a','Personal','Digital','Assistant','that','is','quite','helpful','capable',           #'helping','us','do','many','different','things']        try:        ...
3. Create a program which allows the user to swap individual words in an input string....
3. Create a program which allows the user to swap individual words in an input string. Given a string of input, your program should count and store the number of words in a 2D array. The user can then select the index of the words they want to swap. Your program should swap those two words and then print the entire string to ouput. • Use string prompt "> ". • Use indices prompt "Enter two indices: ". • Remove...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import java.io.*; //This imports input and output (io) classes that we use 3 //to read and write to files. The * is the wildcard that will 4 //make all of the io classes available if I need them 5 //It saves me from having to import each io class separately. 6 /** 7 This program reads numbers from a file, calculates the 8 mean (average)...
Task #4 Calculating the Mean Now we need to add lines to allow us to read...
Task #4 Calculating the Mean Now we need to add lines to allow us to read from the input file and calculate the mean. Create a FileReader object passing it the filename. Create a BufferedReader object passing it the FileReader object. Write a priming read to read the first line of the file. Write a loop that continues until you are at the end of the file. The body of the loop will: convert the line into a double value...
C++ Part B: (String) Program Description: Write a word search program that searches an input data...
C++ Part B: (String) Program Description: Write a word search program that searches an input data file for a word specified by the user. The program should display the number of times the word appears in the input data file. In addition, the program should count and display the number of grammatical characters in the input data file. Your program must do this by providing the following functions : void processFile(ifstream &inFile, string wordSearch, int &wordCount, int &grammaticalCount) ; (15%)...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT