Word Count That Ignores Punctuation And Space
Hi guys. I've spent a really long time writing this program and I'm incredibly stuck. The question is:
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.
The code I've written so far is Code:
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 charcounter = 0;
int finalcount = 0;
String[] wordcount2 = str.split("\\s+");
for (int i = 0; i < str.length(); i++) {
boolean isLetter = Character.isLetter(str.charAt(i));
if (isLetter) {
charcounter++;
if(str.length() >= length){
finalcount++;
}
}
}
System.out.println(wordcount);
System.out.println(charcounter);
System.out.println(finalcount);
}
}
The problem I'm having is printing out the right "finalcount"
If i input: cat dog elephant
and
minimum value 4
the output should be 3 words, 14 characters, 1 word.
However for finalcount, i'm getting 14.
What can I do to compare each WORD in the string to the inputted length?
Thanks
Re: Word Count That Ignores Punctuation And Space