Problem 2 Write your code in the file WordCount.java. Your code should go into a
ID: 3759744 • Letter: P
Question
Problem 2
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
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 countWords method, break the input string up into words and send each one to your method.
Explanation / Answer
public static int countWords(String original, int minLength) {
int wordCount = 0, wordLen;
// splitting the original sentence into array of individual words
// and using for-each loop to iterate word by word
for(String s : original.split(" "))
{
wordLen = 0;
// splitting the word into array of characters
for(char c : s.toCharArray())
{
// checking whether the particular character is letter or not
// if it is letter, counting it into length of word
if((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
{
wordLen++;
}
}
// if letter count of a word meet or exceed the minLength then it is counted into count of words
if(wordLen >= minLength)
{
wordCount++;
}
}
return wordCount;
}
Test Run: countWords(" hi how a@re you doing? I'm fine doing well. ", 4);
output: 4.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.