2012-04-11 2 views
1

숙제 인 경우 Chair 개체를 가져 와서 우리가 만든 DoublyLinkedList에 추가해야합니다. 알파벳 순으로 정렬해야합니다. 알파벳순으로 스타일이 동일하면 색상별로 정렬합니다.compareTo를 사용하는 while 루프가있는 NullPointerException

NullPointerException을 계속 사용하려고합니다.

public void add(Chair element){ 
    if(isEmpty() || first.object.style.compareTo(element.style) > 0 || (first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) >= 0){ 
     addFirst(element); 
    }else if(first.object.style.compareTo(element.style) <= 0){ 
     Node temp = first; 
     Node insert = new Node(); insert.object = element; 
     while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs 
      if(temp.hasNext()) 
       temp = temp.next; 
     while(temp.object.style.compareTo(element.style) == 0 && temp.object.color.compareTo(element.color) <= 0) 
      if(temp.hasNext()) 
       temp = temp.next; 
     insert.prev = temp.prev; 
     insert.next = temp; 
     temp.prev.next = insert; 
     temp.prev = insert; 
    } 
} 

이 내가 DoublyLinkedList

try{ 
     FileReader fr = new FileReader(filename); 
     Scanner sc = new Scanner(fr); 
     String[] temp; 

     while(sc.hasNext()){ 
      temp = sc.nextLine().split(" "); 
      if(temp[0].equals("Bed")){} 
      else if(temp[0].equals("Table")){ 
      // tables.add(new Table(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), temp[4])); 
      }else if(temp[0].equals("Desk")){} 
      else if(temp[0].equals("Chair")){ 
       chairs.add(new Chair(temp[1], temp[2])); 
      }else if(temp[0].equals("Bookshelves")){} 
      else{ 
       color = temp[0]; 
      } 
     } 
     while(!chairs.isEmpty()) 
      System.out.println(chairs.removeFirst().info()); 
     System.out.println(); 
     //while(!tables.isEmpty()) 
     // System.out.println(tables.removeFirst().info()); 
    }catch(Exception e){e.printStackTrace();} 

에 정보를 넣어 코드입니다 이것은 내가 만든 한 DoublyLinkedList 클래스 : 클래스 CDoublyLinkedList { 노드, 성;

public CDoublyLinkedList(){ 
    first = new Node(); last = new Node(); 
    first.prev = last.next = null; 
    first.object = last.object = null; 
    first.next = last; 
    last.prev = first; 
} 

public boolean isEmpty(){ 
    return first.object == null; 
} 

public void addFirst(Chair element){ 
    Node insert = new Node(); 
    insert.object = element; 
    insert.prev = null; 
    insert.next = first; 
    first.prev = insert; 
    first = insert; 
} 

public void add(Chair element){ 
    if(isEmpty() || first.object.style.compareTo(element.style) > 0 || (first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) >= 0){ 
     addFirst(element); 
    }else if(first.object.style.compareTo(element.style) <= 0){ 
     Node temp = first; 
     Node insert = new Node(); insert.object = element; 
     while(first.object.style.compareTo(element.style) <= 0) 
      if(temp.hasNext()) 
       temp = temp.next; 
     while(first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) <= 0) 
      if(temp.hasNext()) 
       temp = temp.next; 
     insert.prev = temp.prev; 
     insert.next = temp; 
     temp.prev.next = insert; 
     temp.prev = insert; 
    } 
} 

public Chair removeFirst(){ 
    Chair tobedeleted = first.object; 
    Node temp = first.next; 
    first = temp; 
    first.prev = null; 
    return tobedeleted; 
} 

private class Node{ 
    Node next, prev; 
    Chair object; 
    public boolean hasNext(){ 
     return next != null; 
    } 
} 

}

의장 클래스 :이 오류가 계속 왜

class Chair extends Furniture{ 
public String style, color; 
public Chair(String s, String c){ 
    style = s; color = c; 
} 
public String toString(){ 
    return color; 
} 
public String getType(){ 
    return "Chair"; 
} 
public String info(){ 
    return (color+", "+style); 
} 
} 

누군가가 나에게 설명시겠습니까? 고맙습니다!

편집 :

while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs 

chairs.add(new Chair(temp[1], temp[2])); 

java.lang.NullPointerException 
at CDoublyLinkedList.add(Furnish2SS.java:119) 
at Furnish2SS.main(Furnish2SS.java:23) 
java.lang.NullPointerException 
at CDoublyLinkedList.add(Furnish2SS.java:119) 
at Furnish2SS.main(Furnish2SS.java:23) 

EDIT2 :이 해결!

while(temp.object != null && element != null && (temp.object.compareTo(element) == 0 || temp.object.compareTo(element) == -1)) 

내가 null 모든 반복에 대해 확인되지 않았기 때문에 오류가 있었다있어 그 이유는

나는 내 while 루프를 변경했습니다.

while(temp.object.style.compareTo(element.style) <= 0) 

당신은 아마 그 줄에 디버거 중단 점을 설정하고 null의 값을 결정하기 위해 디버거를 사용한다 :

+0

내부 개체 중 하나 이상이 첫 번째 또는 개체 또는 스타일로 보이는 것입니다. 내부 예외를 얻으려면 try catch에 루프를 넣으십시오. – legrandviking

+5

뭔가가 null이기 때문에 오류가 발생합니다. 무엇을 찾으려면 stacktrace를보고 예외가 발생한 행이 무엇인지 확인하십시오. – trutheality

+0

프로젝트에서 참조되고있는 개체가 인스턴스화되지 않았거나 null로 설정되어 있습니다. 프로그램을 디버그하고 오류가있는 줄을 알려주십시오. 그러면 문제를 해결하는 데 도움이 될 수도 있습니다. – parion

답변

2

는이 예외를 일으키는 코드 줄 말한다. 그러나 디버거를 설정하고 사용하는 방법에 대한 전체 설명은 여기에서 설명하기가 어렵습니다 (즉, 배우지 말아야한다는 것을 의미하지는 않습니다!) 자습서가 많이 있습니다 .Google에서이 튜토리얼을 작성하는 대신 당신은 당신의 코드의 세 가지 라인을 대체하기 위해 위의 코드 문을 사용하는 경우

if (temp == null) { 
    System.out.println("temp is null"); 
} else if (temp.object == null) { 
    System.out.println("temp.object is null"); 
} else if (temp.object.style == null) { 
    System.out.println("temp.object.style is null"); 
} 

if (element == null) { 
    System.out.println("element is null"); 
} else if (element.style == null) { 
    System.out.println("element.style is null"); 
} 


while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs 
{ 
    if(temp.hasNext()) 
     temp = temp.next; 

    if (temp == null) { 
     System.out.println("loop: temp is null"); 
    } else if (temp.object == null) { 
     System.out.println("loop: temp.object is null"); 
    } else if (temp.object.style == null) { 
     System.out.println("loop: temp.object.style is null"); 
    } 

    if (element == null) { 
     System.out.println("loop: element is null"); 
    } else if (element.style == null) { 
     System.out.println("loop: element.style is null"); 
    } 

} 

: 디버거, 그냥 변수가 null 인 당신을 말할 것이다 코드를 게시 할 수 있습니다

while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs 
     if(temp.hasNext()) 
      temp = temp.next; 

당신은 알게 될 것이다 어떤 명령문이 인쇄되는지에 따라 변수는 널입니다. 잘하면 거기에서 가져갈 수 있습니다. (NullPointerException을 수정하는 일반적인 방법은 프로그램이 NullPointerException의 행에 도달 할 때까지 유효한 null이 아닌 값을 실제로 가지게하는 데 필요한 단계를 수행하는 것입니다.

+0

좋은 답변입니다. 하지만 어쩌면 조금 잔인합니다. –

+0

문제는 그냥 try-catch에 모두 넣었고 예외가 발생하더라도 while 루프의 코드가 작동합니다. 나는 또한 "temp == null"을 확인하려고 시도했지만 아무 것도 출력하지 않았다. – prunes4u

+0

나는 그것을 고쳤다. 어떤 이유로 코드는 정상적으로 실행되지만 NullPointerException이 발생합니다. 방금 스택 추적을 꺼내서 정보를 원하는대로 인쇄합니다. – prunes4u

2

addFirst(Chair element)을 살펴보십시오. 그 방법은 정말 엉망입니다. 올바른 Chair을 포함하는 새로운 Node을 만듭니다. 그런 다음 prevnull으로 설정합니다. 그런 다음 nextfirst으로 설정합니다. 그리고 이것이 모든 문제를 일으키는 원인이됩니다. first은 공백을 가리키기 때문에 Node입니다.당신은 이것으로 끝납니다 :

first은 새로운 Node을 가리 킵니다. 그 중 하나는 이고 어떤 번호도 Chair이 아닙니다. 그 사람은 다시 last을 가리 킵니다.

E : 당신이 당신의 목록을 구현하는 방법에 적어도 두 개의 서로 다른 접근 방식을했고 toghether을 던졌다처럼

전체 코드가 보인다. 더 많은 오류가 있지만 숙제이기 때문에 먼저 수정하려고하면 나쁘지는 않습니다.

수정 방법을 알 수없는 경우 여기에서 질문하십시오.

추신 : 모든 답변을 편집하고 (해제 한) 내 답변 (삭제)을 삭제했습니다. 나는이 모든 것의 진정한 원인이 무엇인지를 마침내 알게 될 때까지 조금 피곤해서 오래되는 것을 고쳐서 새로운 오류를 일으켰다.

+0

+1 받는다. 실제로 코드의 논리를 돕는다. 나는 충분히 용감하지 않았다! –

관련 문제