Question

In: Computer Science

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 wordIsCapitalized that 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.

Solutions

Expert Solution

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:

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

Feel free to rate the answer and comment your questions, if you have any.

Please upvote the answer and appreciate our time.

Happy Studying!!!

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


Related Solutions

Prompt the user to enter an integer Then, prompt the user to enter a positive integer...
Prompt the user to enter an integer Then, prompt the user to enter a positive integer n2. Print out all the numbers that are entered after the last occurrence of n1 and whether each one is even or odd If n1 does not occur or there are no values after the last occurrence of n1, print out the message as indicated in the sample runs below. Sample: Enter n1: -2 Enter n2: 7 Enter 7 values: -2 3 3 -2...
Create in Java a program that will prompt the user to enter aweight for a...
Create in Java a program that will prompt the user to enter a weight for a patient in kilograms and that calculates both bolus and infusion rates based on weight of patient in an interactive GUI application, label it AMI Calculator. The patients weight will be the only entry from the user. Use 3999 as a standard for calculating BOLUS: To calculate the BOLUS you will multiply 60 times the weight of the patient for a total number. IF the...
Create in java a program that will prompt the user to enter a weight for a...
Create in java a program that will prompt the user to enter a weight for a patient in kilograms and that calculates infusion rates based on weight of patient in an interactive GUI application, label it HEPCALC. The patients’ weight will be the only entry from the user. To calculate the infusion rate you will multiply 12 times the weight divided by 50 for a total number. The end result will need to round up or down the whole number....
IN C This assignment is to write a program that will prompt the user to enter...
IN C This assignment is to write a program that will prompt the user to enter a character, e.g., a percent sign (%), and then the number of percent signs (%) they want on a line. Your program should first read a character from the keyboard, excluding whitespaces; and then print a message indicating that the number must be in the range 1 to 79 (including both ends) if the user enters a number outside of that range. Your program...
Write a C program that prompt the user to enter 10 numbers andstores the numbers...
Write a C program that prompt the user to enter 10 numbers and stores the numbers in an array. Write a function, smallestIndex, that takes as parameters an int array and its size and return the index of the first occurrence of the smallest element in the array.The main function should print the smallest number and the index of the smallest number.
Write a C++ program that prompt the user to enter 10 numbers andstores the numbers...
Write a C++ program that prompt the user to enter 10 numbers and stores the numbers in an array. Write a function, smallestIndex, that takes as parameters an int array and its size and return the index of the first occurrence of the smallest element in the array.The main function should print the smallest number and the index of the smallest number.
The program will prompt the user to enter a number between [10 .. 20] (inclusive). After...
The program will prompt the user to enter a number between [10 .. 20] (inclusive). After verifying that the number is within the proper range, you will generate that many random numbers and place them into a dynamically allocated array. Your program will then display the contents of the array (with 4 numbers per line). Next, you will sort the values in descending order (from largest to smallest). Lastly, you will display the sorted numbers (again, with 4 per line)....
A. Write a program 1. Prompt the user to enter a positive integer n and read...
A. Write a program 1. Prompt the user to enter a positive integer n and read in the input. 2. Print out n of Z shape of size n X n side by side which made up of *. B. Write a C++ program that 1. Prompt user to enter an odd integer and read in the value to n. 2. Terminate the program if n is not odd. 3. Print out a cross shape of size n X n...
5) Create the following in a Java program Create a scanner Prompt the user to enter...
5) Create the following in a Java program Create a scanner Prompt the user to enter the name where the box of mail is shipping from and create the variable and relate to scanner Prompt the user to enter the name of destination where the box of mail will be shipped and create the variable and relate to scanner Prompt the user to enter the weight of the package and create variable to relate to scanner Calculate cost of shipping...
(b) You will write a program that will do the following: prompt the user enter characters...
(b) You will write a program that will do the following: prompt the user enter characters from the keyboard, you will read the characters until reading the letter ‘Q’ You will compute statistics concerning the type of characters entered. In this lab we will use a while loop. We will read characters from stdin until we read the character ‘Q’. Example input mJ0*5/]+x1@3qcxQ The ‘Q’ should be included when computing the statistics properties of the input. Since characters are integers...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT