Hello! I'm suppose to code a word counter for my Java class.
The user is suppose to keep entering a sentence until they type "xxx" then at the end, it'd count how many words entered.

It's only counting the "xxx" for me, so at the end, it says I only entered 1 word. Can I get some pointers on how to fix this?

Here's my code:

import java.util.Scanner;
import java.util.StringTokenizer;

public class WordCounter
{
	public static void main(String[]args)
	{
		Scanner keyboard = new Scanner(System.in);
		
		String speech;
		
		do 
		{
			System.out.println("Enter your speech: ");
			speech = keyboard.nextLine();
		}while(!"xxx".equals(speech));

		int counter=0;
		
		StringTokenizer st = new StringTokenizer(speech);
		
		
		while(st.hasMoreTokens())
		{
			System.out.println(st.nextToken());
			counter++;
		}
		
		System.out.println("\nThere are " + counter + " words in the speech.");

	
	}
	
}

Thanks!

1. move line 19 to before line 13.
2. move lines 21-28 to in between lines 16 & 17.

Solved! Thanks so much!

Please mark the thread as solved. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.