Can anyone help me find my error? I am trying to display the words of a text fil
ID: 3622563 • Letter: C
Question
Can anyone help me find my error? I am trying to display the words of a text file in alphabetical order with their associated word counts. I have tried several ways now, but have decided to use the TreeMap because of associated examples in my book. I keep getting a NullPointerException for line 24 (String [] words...). Please give me a little guidance if u can! Thanks![code]import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class WordCounts {
public static void main(String[] args) throws FileNotFoundException, IOException {
if (args.length == 0) {
System.out.println("Usage: java WordCounts targetfile");
}
String inputText = "";
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
try {
String line = null;
while ((inputText = in.readLine()) != null) {
String[] words = line.split("[ .,;:!?(){}]");
for (int i = 0; i < words.length; i++) {
String key = words[i].toLowerCase();
if (words[i].length() > 1) {
if (map.get(key) == null) {
map.put(key, 1);
}
else {
int value = map.get(key).intValue();
value++;
map.put(key, value);
}
}
}
in.close();
}
}
catch (IOException error) {
System.out.println("Invalid File");
}
// Get all entries into a set
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
// Get key and value from each entry
for (Map.Entry<String, Integer> entry: entrySet){
System.out.println(entry.getValue() + " " + entry.getKey());
}
}
}[/code]
Explanation / Answer
From what I can tell, the problem is that you declare line = null, and then never read anything into it. I've put a few comments in the code below: try { String line = null; // This is fine, so line is null... while ((inputText = in.readLine()) != null) { // This line doesn't put anything in line, so line is still null... String[] words = line.split("[ .,;:!?(){}]"); // You're calling a method on a line that is still null--you didn't read anything into it after declaring it null. Try changing your while-loop so that you read into line, instead of inputText.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.