我查看了之前的所有示例,无法看到任何我做错的事情。由于某种原因,我真的很挣空指针异常,我只是无法绕过它们。
public class DLBDictionary implements DictionaryInterface {
//Store Strings in an Node
public DLBNode firstNode;
public class DLBNode
{
public char value;
public DLBNode nextValue;
public DLBNode nextLetter;
public DLBNode(){
this.value = '/';
this.nextValue = null;
this.nextLetter = null;
}
public DLBNode(char value){
this.value = value;
this.nextValue = null;
this.nextLetter = null;
}
}
public DLBDictionary() {
DLBNode firstNode = new DLBNode('/');
}
// Add new String to end of list. If String should come before
// previous last string (i.e. it is out of order) sort the list.
// We are keeping the data sorted in this implementation of
// DictionaryInterface to make searches a bit faster.
public boolean add(String s) {
int charIndex = 0;
while(charIndex<=s.length())
{
char currentChar = s.charAt(charIndex);
boolean added = false;
while(!added)
{
if(firstNode.value == '/')
{
firstNode.value = currentChar;
added = true;
}
else if(firstNode.value == currentChar)
{
if(firstNode.nextLetter == null)
{
DLBNode newNode = new DLBNode();
firstNode.nextLetter = newNode;
firstNode = firstNode.nextLetter;
}
else
{
firstNode = firstNode.nextLetter;
}
added = true;
}
else
{
firstNode = firstNode.nextValue;
}
}
charIndex++;
}
DLBNode tempNode = new DLBNode('^');
firstNode.nextLetter = tempNode;
return true;
}
我离开了我的其余代码,但最后的if语句是我得到异常的地方。对我来说完全是无稽之谈!我没有将firstNode的值初始化为&#39; /&#39;在构造函数中?所以firstNode.getValue应该返回&#39; /&#39;不是空指针异常。
答案 0 :(得分:1)
你应该这样做 this.firstNode = new DLBNode(); 在DLBDictionary的构造函数中。您实际上正在创建一个新对象,而不是初始化您的firstNode。希望它有所帮助。
答案 1 :(得分:0)
You reset firstNode with several statements in the loop:
firstNode = firstNode.nextValue;
因此会发生firstNode == null,这会导致NPE。 char值与它无关,它将被初始化为值为0x00的字符。