2012-04-29 4 views
0

이 코드를 사용하면 데이터가 포함 된 파일을 개체 배열에로드하려고합니다. 이 코드를 실행할 때 NullPointerException이 발생하기 때문에 객체 내의 필드를 제대로 초기화하지 않았습니다. 배열이 있고 거기에 맞는 크기가 있지만 필드가 초기화되지 않았습니다. 이 문제를 어떻게 해결해야합니까?개체 배열이 제대로 초기화되지 않습니다.

public class aJob { 
    public int job; 
    { 
    job = 0; 
    } 
    public int dead; 
    { 
    dead = 0; 
    } 
    public int profit; 
    { 
    profit = 0; 
    } 
} 

public class Main { 
    public static void main(String[]args) throws IOException { 
    File local = readLines(); 
    Scanner getlength = new Scanner(local); 
    int lines = 0; 

    while (getlength.hasNextLine()) { 
     String junk = getlength.nextLine(); 
     lines++; 
    } 
    getlength.close(); 

    Scanner jobfile = new Scanner(local); // check if empty        

    aJob list[] = new aJob[lines]; 
    aJob schedule[] = new aJob[lines]; 
    int index = 0; 
    list[index].job = jobfile.nextInt(); 
    } 

    public static File readLines() throws IOException 
    { 
    try { 
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
    } catch (Exception e) { 
     // ignore exceptions and continue 
    } 

    JFileChooser chooser = new JFileChooser(); 
    try { 
     int code = chooser.showOpenDialog(null); 
     if (code == JFileChooser.APPROVE_OPTION) { 
     return chooser.getSelectedFile(); 
     } 
    } catch (Exception f) { 
     f.printStackTrace(); 
     System.out.println("File Error exiting now."); 
     System.exit(1); 
    } 
    System.out.println("No file selected exiting now."); 
    System.exit(0); 
    return null; 
    } 
} 

답변

5

배열을 선언하는 것만으로는 충분하지 않습니다. 오브젝트 인스턴스로 채워야합니다.

aJob list[] = new aJob[lines]; 
aJob schedule[] = new aJob[lines]; 

for (int i = 0; i < lines; i++){ list[i] = new aJob(); schedule[i] = new aJob(); } 
4

문제는 여전히 널 즉, 배열의 요소가 초기화되지 않는다는 것이다 : 여기

코드이다.

aJob list[] = new aJob[lines]; // creates an array with null values. 
for(int i=0;i<lines;i++) list[i] = new aJob(); // creates elements. 
0

또 다른 가능성은 프로그램에서 배열 대신 ArrayList 또는 LinkedList를 사용할 수 있다는 것입니다. 예를 들어

,

ArrayList<aJob> list = new ArrayList<aJob>(lines); 
ArrayList<aJob> schedule = new ArrayList<aJob>(lines); 

int index = 0; 
list.add(0, new aJob(jobFile.nextInt()); 

은 동일한 작업을 수행합니다. 마지막 줄은 스캐너 객체에서 가져온 값으로 새 aJob 객체를 만든 다음 위치 0에 삽입합니다.

배열은 간단한 구조이지만 목록을 사용하면 유연성이 향상됩니다. 특히 그렇지 않은 경우 얼마나 많은 ajob 요소를 만들 것인지를 아십시오. 배열은 인스턴스화시 크기를 정의해야하지만 목록은 새로운 요소를 처리하기 위해 커질 수 있습니다.

관련 문제