2015-01-31 2 views
0

이전 예제를 모두 살펴본 결과 내가 잘못하고있는 것을 볼 수 없습니다. 왠지 이유로 null 포인터 예외로 고생하고 난 그저 내 머리를 감쌀 수 없다.이중 링크 된 Lisl이 계속해서 null 포인터 오류가 발생합니다.

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는 널 포인터 예외가 아니라 '/'를 리턴해야합니다.

+0

문제가있는 부분이 생략되었습니다. – laune

+0

지금 전체 메서드를 추가했습니다. 나는 이미 firstNode와 currentNode가 문제일지도 모른다고 생각했지만 그게 작동하지 않는 것 같아서 ... –

답변

1

this.firstNode = new DLBNode(); 은 DLBDictionary의 생성자에 있습니다. 실제로는 firstNode를 초기화하는 대신 새 객체를 만듭니다. 희망이 도움이됩니다.

+0

고마워. 나는 지난 50 분을 그걸 알아 내려고 애 쓰면서 당혹 스럽다. 문제가있는 곳에서 느낌이 들었습니다! –

+0

Mike, ok .. :-) –

0
You reset firstNode with several statements in the loop: 

firstNode = firstNode.nextValue; 

따라서 firstNode == null이 발생하여 NPE가 발생합니다. char 값은 아무 관계가 없으며 값이 0x00 인 문자로 초기화됩니다.

관련 문제