Word counter

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.

public static void main(String[] args) throws IOException {

    // Scanner for keyboard input
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter a string to count words: ");

    // Get input from user
    String input = keyboard.nextLine();

    // close keyboard

    int numberOfWords = wordCount(input);

    // Call word count
    System.out.println("The string has " + numberOfWords + " words in it.");

 * Word count should return the number of words contained within a string.
 * @param String
 * @return number of words
static int wordCount(String str) {
    StringTokenizer strTok = new StringTokenizer(str);
    return strTok.countTokens();


Enter a string to count words: flying on a jet plane
The string has 5 words in it.

Level Up

  • Change the interals of wordCount to use a different implementation technique such as guava or java 8.