LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Java String Programs · Question 8

Count words, sentences and characters in a paragraph in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Read a paragraph from input and print the number of words, sentences (ending in . ! or ?), letters and the average word length.

Solution
Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        StringBuilder text = new StringBuilder();
        while (in.hasNextLine()) text.append(in.nextLine()).append(' ');
        String t = text.toString().strip();

        String[] words = t.split("\\s+");
        int sentences = 0, letters = 0;
        for (char c : t.toCharArray()) {
            if (c == '.' || c == '!' || c == '?') sentences++;
            if (Character.isLetter(c)) letters++;
        }
        System.out.printf("words %d, sentences %d, letters %d, average word length %.2f%n", words.length, sentences, letters, (double) letters / words.length);
    }
}

Output Verified by compiling and running

words 15, sentences 4, letters 67, average word length 4.47

All input lines are joined, then split on whitespace for words; sentence and letter counts come from one pass over the characters.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links