Reputation: 1111
I want to create hashtable which would take each String from my array and assign it to unique integer value. My array is read from file and assigned to array like this:
public void readFile() throws Exception{
FileInputStream in = new FileInputStream("words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
wordsList = new String[getNumberOfLines()];
for (int j = 0; j < wordsList.length; j++){
wordsList[j] = br.readLine();
}
in.close();
}
Using this array I wrote method to create hash table like this:
String currentWord;
private Hashtable <String,Integer> wordsHashTable;
LinesReader lr = new LinesReader();
int i;
String[] listOfWords;
public boolean insertValues() throws Exception{
for (i=0; i<lr.getNumberOfLines();i++){
lr.readFile();
listOfWords = lr.returnsWordList();
currentWord = listOfWords[i];
wordsHashTable.put(currentWord, i+1);
}
return wordsHashTable.isEmpty(); //testing purposes only
}
It throws NullPointer exception at line: wordsHashTable.put(currentWord, i+1); Any ideas where I messed up?
Upvotes: 1
Views: 1437
Reputation: 172378
Initialize your hash table. You forgot to initialize it.
private Hashtable <String,Integer> wordsHashTable = new Hashtable<>();
Upvotes: 1
Reputation: 8278
You did not initialized the `Hashtable'.
private Hashtable <String,Integer> wordsHashTable = new Hashtable <String,Integer>();
will fix it.
However, I would recommend you to move to something more modern like a HashMap
Upvotes: 0
Reputation: 200138
You must initialize your wordsHashTable
with an instance of the class:
private Hashtable <String,Integer> wordsHashTable = new Hashtable<>();
However, do note that the Hashtable
class is obsolete; you should use java.util.HashMap
instead.
Upvotes: 3