2014-11-18 2 views
0

이 프로그램에서 NullPointerException이 발생합니다. Object Array를 선언 할 때 문제가 있다고 생각합니다.개체 배열 작업 중 NullPointerException

import java.util.Scanner; 

class One 
{ 
    public static void main(String args[]) 
    { 
     Scanner key = new Scanner(System.in); 
     two[] obj = new two[3]; 

     for (int i = 0; i < 3; i++) { 
      obj[i].roll = key.nextInt(); 
      obj[i].name = key.nextLine(); 
      obj[i].grade = key.nextLine(); 
     } 

     for (int i = 0; i < 3; i++) { 
      System.out.println(obj[i].roll + " " + obj[i].name + " " + obj[i].grade); 
     } 
    } 
} 

class Two 
{ 
    int roll; 
    String name, grade; 
} 
+0

[Null Pointer Exception이란 무엇이며 어떻게 수정합니까?] (http://stackoverflow.com/questions/218384/what-is) -a-null-pointer-exception-and-how-do-i-fix-it) – Raedwald

답변

3

배열의 개체를 초기화하는 것을 잊었습니다. 이 초기화가 없으면 obj[i]에 널 참조가 있습니다.

two[] obj=new two[3]; 
for(int i=0;i<3;i++) 
{ 
    obj[i] = new two(); 
    obj[i].roll=key.nextInt(); 
    obj[i].name=key.nextLine(); 
    obj[i].grade=key.nextLine(); 
} 
0

배열 내부의 개체가 초기화되지 않았습니다. 첫 번째 for 루프에서 주먹 문으로 obj[i] = new Two(); 을 호출하십시오. Btw : "two"는 대문자 "2"여야합니다.