2014-11-17 1 views
0

문자열 배열에 대해 java.lang.NullPointerException이 표시되는 이유를 정확히 모르시겠습니까? 나는 몇 시간 동안 찾았지만 문제를 찾을 수 없습니다. 여기 문자열 배열에 대해 java.lang.NullPointerException이 나타나는 이유는 무엇입니까?

private String[] stringList; 
int j = 0; 
StringClass stringRef = new StringClass(); 

while (//As long as there is string available from what I am reading in) 
{ 
     str = //String read in; 
     stringRef.setString(str); 
     stringList[j] = stringRef.returnString(); //Shows that this line is the error 
     j++; 
} 

클래스입니다 도와주세요 : 그것은 당신의 변수 stringList의 이름에도 불구하고

public class StringClass { 

    private String stringNew; 

    public void setString(String newStr){ 
     stringNew = newStr; 
    } 

    public String returnString(){ 
     return stringNew; 
    } 
} 
+1

당신이'공용 클래스 StringClass {...}를'찾으 셨나요? 여기

내 제안 된 변경 코드인가? 어느 쪽이든, 나는 그것이 당신이 당신의 학급에 이름을 지은 방법이 아니기를 바랍니다! – mystarrocks

+0

그리고'stringList'는 예외를 던지는 시점에서'null'이됩니다. – mystarrocks

답변

0

당신은 List를 사용하지 않았다. 목록은 동적으로 크기가 조정되므로 컴파일 할 때 초기 크기를 선언 할 필요가 없습니다.

import java.util.ArrayList; 
import java.util.List; 

... 

private List<String> stringList = new ArrayList<String>(); 
int j = 0; 
StringClass stringRef = new StringClass(); 

while (//As long as there is string available from what I am reading in) 
{ 
     str = //String read in; 
     stringRef.setString(str); 
     stringList.add(stringRef.returnString()); //Shows that this line is the error 
     j++; 
} 
+0

정말 고마워요. 목록에 추가 된 첫 번째 또는 두 번째를 인쇄하려면 어떻게 목록에 색인을 붙이시겠습니까? –

+0

@OM https://docs.oracle.com/javase/7/docs/api/java/util/List.html#get(int) – Josh

관련 문제