I am trying to validate the format of a date before assigning it to an instance variable in a constructor. Each time, it throws a null pointer exception even though I provide a value for the field each time I try to instantiate an object. I think the problem must be with the parse statement, but I cannot understand why there would be a null value there.
Moreover, I was wondering if it is proper practice to validate a date in the constructor in the first place. Should I have a method doing this instead?
Thank you so much for your help. This is my first exposure to java.
import java.text.*;
public class Photograph {
private String caption;
private final String filename;
private String dateTaken;
private int rating; //declares fields
public Photograph(String caption, String filename) {
this.caption = caption;
this.filename = filename;
this.dateTaken = "1901-01-01";
this.rating = 0; //constructor
}
public Photograph(String caption, String filename, String dateTaken,
int rating) {
this.caption = caption;
this.filename = filename;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
try {
sdf.parse(this.dateTaken);
this.dateTaken = dateTaken;
} catch (ParseException e) {
this.dateTaken = "1901-01-01";
}
}
}
public static void main(String[] args) {
// Testing
//valid date
Photograph test_photo1 = new Photograph("cap1", "pic1", "2017-09-30", 3);
System.out.println(test_photo1.toString());
Photograph test_photo2 = new Photograph("cap2", "pic2", "2017-12-25", 0);
System.out.println(test_photo2.toString());
Photograph test_photo3 = new Photograph("cap3", "pic3", "2018-14-25", 5);
System.out.println(test_photo3.toString());
Photograph test_photo4 = new Photograph("cap4", "pic4", "2018-03-27", 4);
System.out.println(test_photo4.toString());
Photograph test_photo5 = new Photograph("cap5", "pic5", "2018-03-29", 2);
System.out.println(test_photo5.toString());
Photograph test_photo6 = new Photograph("cap6", "pic6", "2018-10-21", 9);
System.out.println(test_photo6.toString());
}