Counting unique words and frequencies from a text file

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
richyw
Messages
179
Reaction score
0

Homework Statement



I need to write a program that takes a text file, and looks for how many unique words it has, as well as the number of times they occur in the file.

Homework Equations



None

The Attempt at a Solution

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

Scanner s = new Scanner(new File("file.txt"));

String[] wordlist = new String[10000];
int[] wordcount = new int[10000];
int i = 0;
do {
String word = s.next();
if (wordlist.equals(null)) {
wordlist = word;
wordcount ++;
} else if (wordlist.equals(word)) {
wordcount ++;
}
i++;
} while (s.hasNext());
}

when I try and do this, it compiles, but when I run it I get an error. how do I get java to check and see if an element of an array is null?
 
Physics news on Phys.org
Is this the line that gives the error?
Code:
if (wordlist[i].equals(null)

The problem is, of course, calling .equals() on a null element. Here's the fix:
Code:
if(wordlist[i] == null)