Reputation: 3
i have no idea what's wrong with what i am doing. It's supposed to print all patients who visited on a specific date but it keeps on throwing the null pointer error. It happens when I call on the printPatientsOnDate method.
code on the main/UI class
public void printPatientsOnDate() throws ParseException
{
System.out.print("Enter the date(mm-dd-yyyy): ");
Date dt = new SimpleDateFormat("MM-dd-yyyy").parse(sc.nextLine());
for(Patient i : app.getPatientsOnSpecDate(dt))
{
System.out.println(i.getName());
}
}
code on the clinic class
public ArrayList<Patient> getPatientsOnSpecDate(Date date)
{
ArrayList<Patient> patients = null;
for(Patient i : patientList)
{
if(i.searchDates(date)!=null)
{
patients.add(i);
}
}
return patients;
}
null pointer error code
Exception in thread "main" java.lang.NullPointerException
at pkg.Pagamutan.Clinic.UI.printPatientsOnDate(UI.java:81)
Upvotes: 0
Views: 710
Reputation: 49352
Your ArrayList<Patient> patients
reference variable is null
. Currently it doesn't point to any ArrayList<Patient>
object .
ArrayList<Patient> patients = null;
And when you trying to invoke .add()
on that null
reference it throws NullPointerException.
Thrown when an application attempts to use null in a case where an object is required.
These include:
Calling the instance method of a null object. .............
You need to instantiate an ArrayList<Patient>
object before invoking .add()
on it.
ArrayList<Patient> patients = new ArrayList<Patient>();
Or better use List<Patient>
as the reference type :
List<Patient> patients = new ArrayList<Patient>();
Upvotes: 1