2013-03-14 6 views
0

Java의 arrayList에 객체를 추가하는 데 문제가 있습니다. 내 코드를 실행할 때 다음과 같은 오류가 발생합니다. 이것은 내 파일 두 조각입니다. 나는 내 오류를 지적 할 사람이 많이 있었을 것이다. 감사합니다, 조arrayList에 객체 추가

java.lang.NullPointerException이 House.addRoom 하우스 (House.java:18). (House.java:36)에서

// 룸 CLASS

public Room() { 
    Scanner scan = new Scanner(System.in); 
    scan.useDelimiter("\n"); 

    System.out.println("Enter description of room:"); 
    description = scan.next(); 

    System.out.println("Enter length of room:"); 
    length = scan.nextDouble(); 

    System.out.println("Enter width of room:"); 
    width = scan.nextDouble(); 
    } 

/ 당신의 arraylist를 초기화하는 요소를 추가하기 전에/하우스 CLASS

public class House { 
    private static ArrayList<Room> abode; 

    public void addRoom(){ 
    abode.add(new Room()); 
    } 
    public House() { 
    idNum = ++internalCount; 
    Scanner scan = new Scanner(System.in); 
    scan.useDelimiter("\n"); 

    System.out.println("Enter address of house:"); 
    address = scan.next(); 

    System.out.println("Enter number of rooms:"); 
    numRooms = scan.nextInt(); 

    System.out.println("Enter type of house:"); 
    houseType = scan.next(); 

    for (int i=1; i<=numRooms; i++){ 
     addRoom(); 
    } 
    } 
} 

답변

3

당신은 it.possibly에 초기화에 필요한 사용자 생성자

private static ArrayList<Room> abode; 

public House() 
{ 
abode = new ArrayList<String>(); 
//rest of your code 
} 

, BTW는 항상 좋은 방법은 구현보다는 인터페이스에 코드 :

즉, List<Room> abode = new ArrayList<String>();

+0

-1 답변을 컴파일하려고 했습니까? – gontard

+0

@gontard 내 편집을 확인 했습니까 ?? :) – PermGenError

+0

nth edit :)? 아니. – gontard

1

을 당신은 목록을 작성해야합니다 :

private static ArrayList<Room> abode = new ArrayList<Room>(); 

을 그렇지 않은 경우 abodenull이고 NullPointerException이 표시됩니다.

또한 abodestatic 인 이유가 있습니까? 즉, 모든 인스턴스 (예 : House)가 공유합니다. 그게 당신이하려는거야?

+0

+1,'static' 수정자를 질문하기 위해. – gontard

0

변경이

private static ArrayList<Room> abode; 

private static ArrayList<Room> abode = new ArrayList<Room>(); 

에 당신은 그것을 위해 메모리를 할당하지 않고 목록 참조를 사용하려고합니다.

0

목록을 사용하여 배열 목록을 추가 할 수 있습니다.

예를 들면 다음과 같습니다. ArrayList results = 새 ArrayList();

목록 < ResolveInfo>

하고

results.add();

0

Joe, 먼저 개체의 필드 나 메서드에 액세스하기 전에 개체를 만들어야합니다.

코드에 private static ArrayList abode; // 객체가 생성되지 않았습니다.

기본적으로 null을 가리키는 참조 만 선언하고 있습니다. 기본적으로 개체의 상태를 저장하기 위해 힙에 메모리를 할당하지 않습니다. 먼저, new 연산자를 사용하여 ArrayList 클래스의 객체를 생성해야하며, 이후에이 객체에 대해 다양한 작업을 수행 할 수 있습니다. 그래서 코드를

으로 바꿉니다.

private static ArrayList abode = new ArrayList();