Write your code in the file WordCount.java. Write your test cases in assign5-tes
ID: 3567876 • Letter: W
Question
Write your code in the file WordCount.java. Write your test cases in assign5-testcases.txt.
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.
Explanation / Answer
Program:
import java.io.*;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
// get user input for string
Scanner sc = new Scanner(System.in);
System.out.print("Input string: ");
String input = sc.nextLine();
System.out.print("Enter min word length: ");
int word_length = sc.nextInt();
int count = 0;
// error checking
if (input.isEmpty() || word_length < 0) {
System.out.println("Wrong Input");
return;
};
// clean up input string using regex magic
String noSpecial = input.replaceAll("[^A-Za-z ]", ""); // keep only alphabetic characters and whitespace
String noPadding = noSpecial.trim(); // remove extra spaces from beginning and end
String normalized = noPadding.replaceAll("\s+", " "); // remove multiple spaces between words
// put each word into an array element
String[] words = null;
words = normalized.split(" ");
// iterate through each array element
for (int i = 0; i < words.length; i++) {
if (words[i].length() >= word_length) {
count++;
};
}
System.out.println(" Count is :"+count));
}
}
---------------------------------------------------------------------------------------------------------
Input string: Gangadhar and Tejaswi are lovers
Enter min word length: 7
Count is : 2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.