gpt4 book ai didi

java - 双向链接 Lisl 不断出现空指针错误

转载 作者:行者123 更新时间:2023-12-01 11:57:24 25 4
gpt4 key购买 nike

我查看了前面的所有示例,看不出我做错了什么。由于某种原因,我真的很挣扎于空指针异常,而且我就是无法理解它们。

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 的构造函数中。您实际上是在创建一个新对象,而不是初始化您的第一个节点。希望对您有所帮助。

关于java - 双向链接 Lisl 不断出现空指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28249201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com