...

View Full Version : Using Arrays To Count Individual Words



evolutiongfx
12-08-2009, 08:32 PM
I have a start on a code which is:



/**
* @author
* @version December 8, 2009
*/
import java.util.*;
import java.io.*;

public class WordCount
{
// instance variables - replace the example below with your own
/**
* Constructor for objects of class WordCount
*/
public WordCount()
{
// initialise instance variables
}

public static void countWords()
{
final String filename = ("/users/owner/desktop/WordCount.txt");

try
{
FileReader fileHandle = new FileReader("/Users/Owner/Desktop/WordCount.txt");
Scanner infile = new Scanner(fileHandle);
String next;

while (infile.hasNext())
{
next = infile.next();
System.out.println(next);
}

infile.close();
}
catch (FileNotFoundException exception)
{
System.out.format("Cannot open %s for reading", filename);
}
}
}

Which compiles and correctly outputs the WordCount.txt file as it is:


msu
is
the
only
Carnegie
tier
1
university
in
our
five
state
region
this
is
another
line
in
the
file
which
has
less
than
five
lines

With each word getting it's own line.

Now, my problem is, I'm not sure how to combine the words to only show once (i.e. only show the word "the" once, with a ": (number of times the words has appeared)" next to it.

By the way, this is what the assignment says:


To do this have two local arrays in your method, words, which is a String[100]
array and count, which is an int[100] array. (There wonít be more than 100
unique words in the file.) Each time you read in a new word using next() first
scan through the values currently in the words array to see whether it is already
there. If it is, then add one to the value in count with the same index. If it isnít
then add the word to the words array and set the corresponding count element to
1. As you have in previous programs youíll need a variable called, say, nextIndex,
which is initially zero and gives the next available location in the array.

Any help would be appreciated.

Philip M
12-08-2009, 08:39 PM
This is the JavaScript forum. Java and Javascript are entirely different programming languages, in spite of the confusingly similar names.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum