In: Computer Science
Write a Java program to read in text line by line until a blank line is entered. When this occurs the program returns the total number of words and characters found as shown in the example below.
A program to count the number of words and characters in an input text block.
Enter text line by line; blank line to end.
>> This is the first line of text
>> Followed by the second line of text
>> Ending with the final line of text
>>
Your text contained 21 words and 81 characters.
Your program should be able to reproduce this example (Note that text following the >> prompt is user input to the program).
Instructions
1. Start by writing a method, countLine, to count the number of words and characters in a string. It should have the following signature:
private countObject countLine(String input) {
which returns the total number of words and characters in the input string, where countObject is a simple nested class similar to listNode with two instance variables corresponding to the number of words and characters respectively.
class countObject {
int words;
int chars;
}
Hint: you might consider adding a constructor to initialize this object and getter methods to retrieve each component.
2. Write a main class which implements the user dialog shown in the example. It calls the countLine method to process each line read and adds the counts returned in countObject to the totals. Call this class wordCount.
Hints: You may use that acm.jar is available; the StringTokenizer class can greatly simplify the coding of the countLine method.
Do your coding in Eclipse. Cut and paste wordCount.java into the space provided on the exam.
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== import java.util.Scanner; public class Main { class countObject { int words; int chars; public countObject(String line) { words = line.split("\\s+").length; chars = line.length() - words + 1; } public int getWords() { return words; } public int getChars() { return chars; } } private countObject countLine(String input) { countObject co = new countObject(input); return co; } public static void main(String[] args) { Main mc = new Main(); Scanner scanner = new Scanner(System.in); System.out.println("Enter text line by line; blank line to end.\n" + "\n"); int words = 0, characters = 0; String input; do { input = scanner.nextLine(); countObject co = mc.countLine(input); words += co.getWords(); characters += co.getChars(); } while (input.length() != 0); System.out.println("Your text contained " + (words-1) + " words and " + characters + " characters."); } }
==============================================================