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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!