Having trouble with CSC assignment. Trying to make an array of Strings

AI Thread Summary
The discussion revolves around a programming assignment requiring the creation of a Java program to count unique words and their occurrences from a text file. The user attempts to implement this using two arrays: one for the words and another for their counts. An error arises when checking for null elements in the wordlist array, as using .equals() on a null reference leads to a runtime exception. The correct approach is to use the equality operator (==) to check for null instead. This adjustment resolves the compilation issue and allows the program to function as intended.
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)
 

Similar threads

Replies
5
Views
3K
Replies
10
Views
11K
Replies
1
Views
1K
Replies
2
Views
1K
Replies
12
Views
2K
Replies
6
Views
3K
Replies
7
Views
2K
Back
Top