Here is the code I have.
This is my PrintToFile class
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();
}
}
in my main class here is my call to print my ArrayList
PrintToFile printer = new PrintToFile();
printer.printExp(expList);
I have defined expList as an ArrayList of objects
The exception I get is a
Exception in thread "main" java.lang.NullPointerException
occuring where marked. My question is what is causing this exception? Thanks
You are not creating object of
pwwhich is class field but you are creating object ofpwwhich is local to methodPrintToFile(). So by defaultPrintToFile.pwis null and you getNPE.Change your method to following or initialize
pw,fandfwin constructor(recommended):