gpt4 book ai didi

java - 数字尝试 (JAVA) - 线程 "main"java.lang.ArrayIndexOutOfBoundsException : -13 中出现异常

转载 作者:行者123 更新时间:2023-11-30 02:56:51 24 4
gpt4 key购买 nike

因此,我正在为我的一个项目测试一些来自互联网的有关数字尝试的代码,并且我坚持使用这个代码,因为我尝试的所有操作都会返回此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -13

这是我找到此代码的地方 ( Code Source )

TrieNode.java

class TrieNode {
TrieNode[] arr;
boolean isEnd;
// Initialize your data structure here.
public TrieNode() {
this.arr = new TrieNode[26];
}
}

Trie.java

public class Trie {
private TrieNode root;

public static void main(String[] args) {
Trie tr = new Trie();
tr.insert("TEST");
System.out.println("TEST " + tr.search("TEST"));
}

public Trie() {
root = new TrieNode();
}

// Inserts a word into the trie.
public void insert(String word) {
TrieNode p = root;
for(int i=0; i<word.length(); i++){
char c = word.charAt(i);
int index = c-'a';
if(p.arr[index]==null){
TrieNode temp = new TrieNode();
p.arr[index]=temp;
p = temp;
}else{
p=p.arr[index];
}
}
p.isEnd=true;
}

// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode p = searchNode(word);
if(p==null){
return false;
}else{
if(p.isEnd)
return true;
}

return false;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode p = searchNode(prefix);
if(p==null){
return false;
}else{
return true;
}
}

public TrieNode searchNode(String s){
TrieNode p = root;
for(int i=0; i<s.length(); i++){
char c= s.charAt(i);
int index = c-'a';
if(p.arr[index]!=null){
p = p.arr[index];
}else{
return null;
}
}

if(p==root)
return null;

return p;
}
}

输出:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -13
at Trie.insert(Trie.java:20)
at Trie.main(Trie.java:6)

编译:

javac TrieNode.java Trie.java
java Trie

有什么想法可以解决这个问题吗?

最佳答案

int index = c - 'a'for 循环的第一次迭代期间正在处理 char 'T'

char 值而言,'T' - 'a' = -13,因此 index = -13 会引发异常检查数组时。

编辑:

您的解决方案不起作用,因为您使用的是大写字母。在本文中,程序仅使用“a”到“z”。您可以轻松更改代码以适应这种情况:

char c = Character.toLowerCase(word.charAt(i));

关于java - 数字尝试 (JAVA) - 线程 "main"java.lang.ArrayIndexOutOfBoundsException : -13 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37012811/

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