【发布时间】:2023-09-25 12:44:01
【问题描述】:
我有一个 TrieNode 类,它定义了我的 trie 节点。 我有一个使用 TrieNode 构建 trie 的 trie 类。 我的意图是将字符串插入到 trie 中。我不明白为什么我的程序的输出为空。有一些我无法理解的非常根本的错误!在主类搜索中返回假...我期待真。对于 x 的每个值,下一个 for 循环都返回 false。我期待 x = 7 为“not null”,因为“h”存储在 7。
TrieNode 类:
package trie;
public class TrieNode {
int colour;
char letter;
TrieNode child[];
public TrieNode(int colour, char letter, int len){
this.colour = colour;
this.letter = letter;
this.child = new TrieNode[len];
}
public TrieNode(int len){
this.colour = 0;
this.letter = '\\';
this.child = new TrieNode[len];
}
public int getColour(){
return this.colour;
}
public void setColour(int colour){
this.colour = colour;
}
public char getLetter(){
return this.letter;
}
public void setLetter(char letter){
this.letter = letter;
}
public TrieNode getChild(int x){
return this.child[x];
}
}
我的 Trie 类:
package trie;
public class Trie {
TrieNode root;
public Trie(int len){
root = new TrieNode(len);
}
public void insert(String str){
str = str.toLowerCase();
int length = str.length();
TrieNode temp = root;
for (int x = 0; x < length; x++){
char ch = str.charAt(x);
temp = temp.getChild((int)ch-97);
System.out.println((int)ch-97);
if(temp==null){
temp = new TrieNode(0,ch,26);
}
if(temp!=null){
System.out.println(temp.getLetter());
}
if(x==length-1){
temp.setColour(1);
}
}
}
public boolean search(String str){
str = str.toLowerCase();
int length = str.length();
TrieNode temp = root;
for(int x = 0; x<length; x++){
char ch = str.charAt(x);
temp = temp.getChild((int)ch-97);
if(temp==null || (x==length-1 && temp.getColour()==0)){
return false;
}else{
System.out.println(temp.getLetter());
}
}
return true;
}
}
主类:
package trie;
public class Main {
public static void main(String[] args) {
Trie trie = new Trie(26);
trie.insert("hello");
System.out.println(trie.search("hello"));
for(int x=0;x<=25;x++){
System.out.println(x+" "+trie.root.getChild(x));
}
}
}
【问题讨论】:
-
堆栈跟踪在哪里以及您在哪里获得 NPE?
-
上述代码中没有。但是对于 x 的所有值, trie.root.getChild(x) 都是空的。 trie.insert("hello") 应该在 trie.root.child[7] 中插入 'h' 并且它不应该为空,因为该节点在 insert(String) 函数中被初始化!
标签: java nullpointerexception trie