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

Click For Summary
SUMMARY

The forum discussion centers on a Java programming assignment requiring the creation of an array of Strings to count unique words and their occurrences from a text file. The user initially attempts to check for null elements using the .equals() method, which leads to a runtime error. The correct approach is to use the equality operator (==) to check for null values, specifically with the condition if(wordlist[i] == null) to avoid the error.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of arrays in Java
  • File handling in Java using Scanner
  • Basic knowledge of null checks in Java
NEXT STEPS
  • Learn about Java array initialization and management
  • Explore Java's Collections Framework for dynamic data structures
  • Study file I/O operations in Java for better file handling
  • Investigate error handling and debugging techniques in Java
USEFUL FOR

Students learning Java programming, educators teaching data structures, and developers seeking to improve their file handling and error-checking skills in Java.

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 ·
Replies
5
Views
3K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 10 ·
Replies
10
Views
12K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K