2012-12-28 3 views
1

여기에 제가 가진 코드가 있습니다.Java 파일로 ArrayList를 인쇄 할 클래스를 만듭니다

이 여기 내 메인 클래스 내 PrintToFile이 클래스

import java.util.*; 
import java.io.*; 

public class PrintToFile{ 
     File f; 
     FileWriter fw; 
     PrintWriter pw; 

    public void PrintToFile()throws Exception{//remove void from constructor 
     File f = new File ("Output.txt");//dont reinitialize 
     FileWriter fw = new FileWriter(f, true);//dont reinitialize 
    PrintWriter pw = new PrintWriter(fw);//dont reinitialize 
    } 

    public void printExp(ArrayList<Expense> expList){ 
     for(int i = 0; i < expList.size(); i++){ 
     pw.println("---------------------------------------");//exception here 
     pw.println(expList.get(i)); 
     } 
     pw.close(); 
    } 
} 

이다 나는 개체

예외의 ArrayList를로 expList을 정의

PrintToFile printer = new PrintToFile(); 
    printer.printExp(expList); 

내 ArrayList를 인쇄하기 위해 내 전화입니다 나는 ~이다

Exception in thread "main" java.lang.NullPointerException 
0 표시된 곳에서

이 발생합니다. 내 질문은이 예외의 원인이 무엇입니까? 감사합니다

+0

모두에게 감사드립니다. downvote에 대해 확실하지 ?? 하지만 모든 답변 덕분에 지금은 완벽하게 작동합니다. –

+0

+1 어쩌면 누군가가 들여 쓰기 스타일에 대해 징징 대고 있습니다.) – paiego

+0

변수를 "선언"할 때마다 (예 : File - 데이터를 변수 앞에 놓음)) 새로운 변수를 만듭니다. 따라서 File 유형의 "f"라는 변수가 2 개 있습니다. 변수가 선언되면 변수를 둘러싸는 범위가 중괄호로 묶여 있습니다. 대괄호가 종료되면 변수는 범위를 벗어납니다. 변수 이름이 충돌하면 가장 작은 범위가 우선합니다. 따라서 PrintToFile() 생성자의 "File f"가 "File f"클래스 변수를가립니다. – paiego

답변

3

pw 개체는 클래스 필드가 아니지만 PrintToFile()에 로컬 인 pw의 개체를 만들고 있습니다. 따라서 기본적으로 PrintToFile.pw은 null이고 사용자는 NPE이됩니다.

이 다음에 당신의 방법을 변경하거나 생성자 pw, ffw를 초기화

(권장) :

public void PrintToFile() throws Exception { 
     f = new File ("Output.txt"); 
     fw = new FileWriter(f, true); 
     pw = new PrintWriter(fw); 
} 
1

대신에 :

File f = new File ("Output.txt"); 
FileWriter fw = new FileWriter(f, true); 
PrintWriter pw = new PrintWriter(fw); 

마십시오 다음과 같이

f = new File ("Output.txt"); 
fw = new FileWriter(f, true); 
pw = new PrintWriter(fw); 

로컬 변수를 다시 선언하고 있습니다. n 생성자. 인스턴스 변수는 기본값 (즉, null)에 의해 초기화 된 채로 남아 있습니다.

1

pw가 생성자에서 전역 변수로 설정되지 않았습니다. 생성자를 수정하십시오. void가되어서는 안됩니다.

import java.util.*; 
import java.io.*; 

public class PrintToFile 
{ 
    File f; 
    FileWriter fw; 
    PrintWriter pw; 

    public PrintToFile() throws Exception{ 
     f = new File ("Output.txt"); 
     fw = new FileWriter(f, true); 
     pw = new PrintWriter(fw); 
    } 

    public void printExp(ArrayList<Expense> expList) 
    { 
     for(int i = 0; i < expList.size(); i++) 
     { 
      pw.println("---------------------------------------");//exception here 
      pw.println(expList.get(i)); 
     } 
     pw.close(); 
    } 
} 
1

void (생성자에 void 또는 반환 값 유형이 없음)을 제거하십시오. 그리고 declarete 변수는 한 번만 사용하십시오.

import java.util.*; 
import java.io.*; 

public class PrintToFile 
{ 
    File f; 
    FileWriter fw; 
    PrintWriter pw; 

    public PrintToFile() throws Exception 
    { 
     f = new File ("Output.txt"); 
     fw = new FileWriter(f, true); 
     pw = new PrintWriter(fw); 
    } 

    public void printExp(ArrayList<Expense> expList) 
    { 
     for(int i = 0; i < expList.size(); i++) 
     { 
      pw.println("---------------------------------------"); 
      pw.println(expList.get(i)); 
     } 
     pw.close(); 
    } 
}