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?
You must initialize your
wordsHashTablewith an instance of the class:However, do note that the
Hashtableclass is obsolete; you should usejava.util.HashMapinstead.