2 Word Counter Write a method that accepts a String object a
2. Word Counter
Write a method that accepts a String object as an argument and returns the number of
words it contains. For instance, if the argument is “Four score and seven years ago” the
method should return the number 6. Demonstrate the method in a program that asks the
user to input a string and then passes it to the method. The number of words in the string
should be displayed on the screen.
Solution
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 :
Four score and seven years ago
Word Count is 6
