2014-09-17 7 views
0

오늘이 복습 테스트에서는 Dress와 TestClass의 두 클래스를 만들어야했습니다. 나는이 클래스들을 끝내었지만 프로그램을 실행하려고 할 때 NullPointerException 메시지가 발생했습니다. 여기 내 클래스는 다음과 같습니다NullPointerException 문제

클래스 드레스 :

public class Dress { 
    String colors []; 
    int sizes []; 

    public Dress (String colors [], int sizes []){ 
     this.colors = new String [colors.length]; 
     this.sizes = new int [sizes.length] ; 
     this.colors = colors; 
     this.sizes = sizes; 
    } 

    public boolean search (String color){ 
     for (int i =0; i<colors.length;i++) 
      if (colors [i].equals(color)) 
       return true; 
     return false; 
    } 
    public boolean search (int size){ 
     for (int i =0; i<sizes.length;i++) 
      if (sizes [i] == size) 
       return true; 
     return false; 
    } 
} 

클래스 테스트 : 참고로

public class Tests { 
    public static void main (String args []){ 
     String color[] = {"Pink","Blue","Red"}; 
     int size[] = {8,9,7}; 
     Dress d = new Dress (color, size); 
     System.out.println(d.search("Pink")); 
     System.out.println(d.search(8)); 
    } 
} 
+0

받은 오류에 대해 질문하는 경우 - 오류 메시지 (예외 및 스택 트레이스)를 제공해주십시오. – LionC

+6

NPE를 디버깅하는 방법에 대해 알아야합니다. 이 키는 예외의 행 번호를 알려주는 예외 스택 추적에 있습니다. 해당 줄의 변수를 확인하고 null 인 변수를 찾은 다음 코드를 확인하여 이유를 확인하십시오. 여전히 도움이 필요하면 예외 스택 추적 텍스트 * here *를 게시하고 * us *에게 예외를 throw하는 줄을 알려줘야합니다. 생성자의 처음 두 줄은 필요하지 않으며 오도 된 내용이므로 제거하십시오. –

+1

이'this.colors = new String [colors.length];와'this.sizes = new int [sizes.length];'는 제거 될 수 있습니다. 그건 그렇고, 당신의 코드가 작동합니다. – Tom

답변

1

- 그것은 개인 데이터 멤버로 변경 가능한 참조를 할당하는 나쁜 생각이다 :

this.colors = new String [colors.length]; // The new reference is discarded after reassignment on next line 
this.colors = colors; // The program that passes this reference can modify it; changes will be visible to your class instance. 

참고 문헌을 확인하고 상태를 변경하는 사람은 개인 상태와 상관없이 인스턴스 데이터 멤버를 변경합니다.

여기 (하나의 명확성을 위해)을 할 수있는 올바른 방법이다 :

public Dress(String [] colors) { 
    if (colors == null) throw new IllegalArgumentException("colors cannot be null"); 
    this.colors = new String[colors.length]; 
    // Copy the values from the parameter array into the new, private array. 
    System.arraycopy(colors, 0, this.colors, 0, this.colors.length); 
} 

당신은 항상 개인, 가변 데이터의 방어 복사본을 만들어야합니다.

+0

당신은 처음에는 두 선이 필요 없다고 강사에게 이야기했지만, 그녀는 그것을 고집했습니다. 그녀는 생성자 메서드의 3 행과 4 행에서 볼 수있는 배열에 매개 변수의 값을 할당해야한다고 말했습니다. 하지만 어떤 이유로 3 번째 줄과 4 번째 줄을 무시하고 NullPointerException을 보냈습니다. – Boshokai

+3

강사 나 당신이 이야기 한 내용에 신경 쓰지 않습니다. 내가 제시 한 것은 그 배열을 초기화하는 올바른 방법이다. – duffymo

+0

이 말을하는 좋은 방법은 분명히 처음 두 줄을 읽지 않았다는 것입니다. 나는 한 가지 질문을 던졌지 만 이제는 답을 찾지 못했습니다. – Boshokai