I am trying to count words. It should count the same word once instead of twice. I can't seem to figure that out.

import java.util.*;
public class WordCount {

	public static void main (String[]args)
	

	{
		final int LINES = 6;
		Scanner in = new Scanner(System.in);
		String paragraph = "";
		System.out.println("Please input " + LINES + " lines of text. ");
		for (int i = 0; i < LINES; i+=1)
			
		{
			paragraph = paragraph + " "+ in.nextLine();
		}
		
		System.out.println(paragraph);
		int howlong = paragraph.length();
		System.out.println(+howlong);
		
		String word = " ";
		
		int wordCount = 0;
		
		for (int i = 0; i < paragraph.length(); i+=1)
		{
			if (paragraph.charAt(i) != ' ')
			{
				word ="";

				
				if (paragraph.charAt(i+1) == ' ' || i+1 == paragraph.length()-1)
				{
					
					System.out.println(word);
					wordCount ++;
					word = "";
				}
			}
		}
		System.out.println("The number of words = " + wordCount);
	}
	
}

Can you show the input and output of the program and describe what is wrong with the output and say what the output should be?

It should count the same word once instead of twice.

How are you keeping track of what words have been counted so that you don't count them again?

The code is very confusing. You should better try to use a while() instead of 'if'.

Here's an example:

while(paragraph[i]!=' ')i++;...

Try to enter this code in yours. you will need another while for reading all spaces if there is more than one together.

you could use a vector that stores strings and then compare the current word to the words in the vector and if the word already appears then you don't increase the count while if the word does not appear you add it to the vector and increase the word count

well it's code that was given to me to fix as a homework for a class. The input asks a user to input 6 lines of text. One by one after an enter. Then it counts the words and the output shows 6. It counts the words correctly as the last if statement in the code. I am not sure how to make it count the same word once.

Hi,

Why don't you use a Set to keep track of all unique words. Maybe something like this:

Set<String> words = new TreeSet<String>();

and then in your code you would just have

words.add( word );

The number of words should be the same as the size of the set.

Hope this helps :)

Comments
Good Solution

I think you should use split function , to split your paragraph into tokens .

then go through the array you made -by split - Define ArrayList or Vector or some thing like that.

if the value of the String not exist in the ArrayList add it if exist continue .

at the end you return the size of ArrayList .

another solution use SET and return the size of Set directly .

i hope this help you .

The code as posted does not look at or count any words. It needs some work to first find a word and then to count the words.

This article has been dead for over six months. Start a new discussion instead.