Write a program that takes a string containing a sentence or a set of sentences, and counts the number of words in the sentence that meet or exceed a specified minimum length (in letters). For example, if the minimum length entered is 4, your program should only count words that are at least 4 letters long.
Input the string and the minimum word length (integer), in that order, and output the word count (integer). Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your main program, break the input string up into words and send each one to your method.
public class WordCount {
public static void main(String[] args) {
System.out.println("Enter string: ");
String str = IO.readString();
System.out.println("Enter minimum length: ");
int length = IO.readInt();
int wordcount = str.split("\\s+").length;
int counter = 0;
boolean isletter;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ' || str.charAt(i) == '!') {
isletter = false;
}
else {
counter++;
}
}
{
}
}
}
So far, I'm able to count the number of words (although I'm not really sure if I even need that for this problem) and the number of letters without ONE space. However, I have a few questions.
In this line,
if (str.charAt(i) == ' ' || str.charAt(i) == '!') {
How do I account for multiple spaces and other symbols? Such as if the user inputs: the cat !?@ dog.
Another question I have is how am I supposed to compare the length of EACH word to the minimum length the user inputted?
Any help would be appreciated. I'm just not sure how to get around these issues.

New Topic/Question
Reply



MultiQuote




|