Alex
Alex

Reputation: 21

how can I count number of words from each paragraph from the file in my code java?

Could you help me to add an additional check to this code that would help me to find the number of words from each paragraph?

enter code here

String path = "C:/CT_AQA - Copy/src/main/resources/file.txt";

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));

String line = " ";
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int countNotLetter = 0;
int letterCount = 0;
int wordInParagraph = 0;

while ((line = br.readLine()) != null) {
    if (line.equals("")) {
       paragraphCount++;
    } else {
        characterCount += line.length();
        String[] wordList = line.split("\\s+");
        countWord += wordList.length;
        String[] sentenceList = line.split("[!?.:]+");
        sentenceCount += sentenceList.length;
        String[] letterList = line.split("[^a-zA-Z]+");
        countNotLetter += letterList.length;
    }

    letterCount = characterCount - countNotLetter;
}
br.close();
System.out.println("The amount of words are " + countWord);
System.out.println("The amount of sentences are " + sentenceCount);
System.out.println("The amount of paragraphs are " + paragraphCount);
System.out.println("The amount of letters are " + letterCount);

} java

Upvotes: 0

Views: 73

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19565

The total count of words in paragraphs should be the same as the total count of words wordCount from all lines.

If the number of words per paragraph has to be counted, then wordsInParagraph should be the list of integers List<Integer> wordsPerParagraph which may be counted like this:

int wordInParagraph = 0;
List<Integer> wordsPerParagraph = new ArrayList<>();

while ((line = br.readLine()) != null) {
    if (line.equals("")) {
       paragraphCount++;
       wordsPerParagraph.add(wordInParagraph);
       wordInParagraph = 0;
    } else {
        characterCount += line.length();
        String[] wordList = line.split("\\s+");
        countWord += wordList.length;
        wordInParagraph += wordList.length; // !!!

        String[] sentenceList = line.split("[!?.:]+");
        sentenceCount += sentenceList.length;
        String[] letterList = line.split("[^a-zA-Z]+");
        countNotLetter += letterList.length;
    }

    letterCount = characterCount - countNotLetter;
}
// in case the last paragraph does not have trailing empty line
if (wordInParagraph != 0) {
   wordsPerParagraph.add(wordInParagraph);
}

Upvotes: 0

Related Questions