2016-05-03 39 views
1

所以我正在測試一些來自互聯網的關於Digital Tries的代碼,因爲我有一個項目,嘗試返回此錯誤:數字化嘗試(JAVA) - 線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:-13

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; 
    } 
} 

輸出:

​​

編譯:

javac TrieNode.java Trie.java 
java Trie 

任何想法來解決這個問題?

回答

3

int index = c - 'a'正在對焦炭'T'

根據char的值,'T' - 'a' = -13,因此index = -13在檢查數組時引發異常。

編輯:

您的解決方案是行不通的,因爲你使用大寫字母。在文章中,程序只使用'a'到'z'。你可以很容易地改變你的代碼,以適應這一點:

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

你已經確診的問題,現在添加一個解決方案。 – rgettman

+0

我可以用什麼來代替? int index = c - '0'? –

+0

@rgettman他沒有要求解決方案。事實上,他並沒有要求任何事情! –

-1

請您插入foreloop應該你for循環的第一次迭代過程中使用lenght-1而不是

public TrieNode searchNode(String s){ 
     TrieNode p = root; 
     for(int i=0; i<s.length()-1; 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; 
    } 
+0

嘗試過,但我得到同樣的事情再次 –

相關問題