The problem
Write a method that accepts String objects as an argument and returns the number of words a string contains. Demonstrate the method in a program that asks the user to input a string and passes it to the method. The number of words should be displayed in the screen. The tricky requirement is understanding what delimiter the string should be split on. For instance, should the string be split on whitespace or split on length. For this exercise the requirement will be to split the String on whitespace.
Breaking it down
Creating a Scanner
to read the keyboard input we will ask the user to enter in a string. Next wordCount()
method will process the parameter string and determine how many words are in string by breaking on whitespace storing the value in a variable named numberOfWords
. Finally displaying this information to the user.
Output
Level Up
- Change the interals of
wordCount
to use a different implementation technique such as guava or java 8.