Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Question: Write your code in the file WordCount.java. Your code should go into a

ID: 3759823 • Letter: Q

Question

Question:

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.

I don't know what's wrong with my code, it is returning one word less than what it should be everytime. Also, it's not checking to see if the characters in the substrings are letters:

public class WordCount{  
   public static void main(String[] args){
       System.out.println("Insert string and minimum length of words looking for.");
       System.out.println(countWords(IO.readString(), IO.readInt()));
   }
      
   public static int countWords(String original, int minLength){          
       int numOfWords = 0;
       int index = original.indexOf(" ");
          
       while (index > 0){
           String word = original.substring(0, index + 1);
           if (word.length() >= minLength)
               numOfWords++;
               original = original.substring(index + 1);
               index = original.indexOf(" ");
       }
       return numOfWords;
   }
}

Explanation / Answer

public class WordCount{
public static void main(String[] args){
System.out.println("Insert string and minimum length of words looking for.");
System.out.println(countWords(IO.readString(), IO.readInt()));
}
  
public static int countWords(String original, int minLength){
int numOfWords = 0;
int index = original.indexOf(" ");
  
while (index > 0){
String word = original.substring(0, index + 1);
if (word.length() >= minLength)
numOfWords++;
original = original.substring(index + 1);
index = original.indexOf(" ");
}
return numOfWords;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote