Hi, I'm a beginner in java.
I have to 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.
This is the code that I have written:
public class WordCount { public static void main(String [] args){ System.out.println("Enter a sentence:"); String sentence = IO.readString(); System.out.println("Enter the word length limit"); int limit = IO.readInt(); int sentencelength = sentence.length(); System.out.println("The sentence length is:" + sentencelength); int lettercount = 0; int finalcount = 0; for (int i=0; i < sentencelength; i++){ if (sentence.charAt(i) == ' '){ if (lettercount >= limit){ finalcount ++; lettercount = 0; } }else{ if(Character.isLetter(sentence.charAt(i))){ lettercount ++; } } } System.out.println("The number of words with a length of" + limit); IO.outputIntAnswer(finalcount); } }
If I input the string "The cow jumped over the barn and under the moon" and I input a limit of 2, my output should be 10. But my program is outputting 9. I figured out [by using system.out.println()]that my program does not count the letters of the last word in a sentence. How do I fix this bug?
Sorry, I'm new to this forum. I didn't know how to post my code. Is this better?