我查看了之前的所有示例,看不到我做错了什么。出于某种原因,我真的很挣扎于空指针异常,我只是无法绕过它们。
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 的值初始化为"/"吗?所以firstNode.getValue应该返回'/',而不是空指针异常。
你应该这样做this.firstNode = new DLBNode();在 DLBDictionary 的构造函数中。您实际上是在创建一个新对象,而不是初始化您的第一个节点。希望对您有所帮助。
You reset firstNode with several statements in the loop:
firstNode = firstNode.nextValue;
因此,第一节点 == null 会导致 NPE。char 值与它无关,无论如何它都会初始化为值0x00的字符。