Write a method in Java named wordCount which takes a string and returns the numb
ID: 3585990 • Letter: W
Question
Write a method in Java named wordCount which takes a string and returns the number of words in it. You may assume that the string contains only letters, digits, punctuation, or spaces. You may also assume that words are always separated by spaces. If two words are separated by multiple spaces, they still are only two words (so you cannot just count the number of spaces!). Everything that is not a space, including digits and punctuation, is considered part of a word. Examples: wordCount("This is a test") wordCount("This is a wordCount("") returns 0 wordCount("Wahoo42!??!?!") returns 4 test!!!!!") returns 1 returns 4
Explanation / Answer
WordCountTest.java
import java.util.Scanner;
public class WordCountTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the string :");
String str = in.nextLine();
int count = wordCount(str);
System.out.println("Word Count is "+count);
}
public static int wordCount(String str){
String words[] = str.split("\s+");
return words.length;
}
}
Output:
Enter the string :
This is a wordCount(
Word Count is 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.