Write your code in the file WordCount.java. Your code should go into a method wi
ID: 3759832 • Letter: W
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.
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
import java.io.*;
import java.util.*;
class WordCount
{
public static int countWords(String original, int minLength)
{
int len = original.length(), currentLength = 0; //Initialize the len to length of string. currentLength to 0.
int wordCount = 0; //Initialize wordCount to 0.
for(int i = 0; i < len; i++) //For every character.
{
if(original.charAt(i) == ' ') //If the character is space, which means word ended.
{
if(currentLength >= minLength) //If that word meets minimum length
wordCount++; //Increment word counter.
currentLength = 0; //Update the currentLength to 0.
}
if(Character.isLetter(original.charAt(i))) //If read character is an alphabet.
currentLength++; //Increment the currentLength.
}
if(currentLength >= minLength) //After coming out of the loop, this is for last word.
wordCount++;
return wordCount;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String sentence = in.nextLine();
System.out.print("Enter the minimum length: ");
int min = in.nextInt();
System.out.println("The number of characters, meeting the minimum length is: "+countWords(sentence, min));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.