Converting Gregorian Calendar to String but throwing an exception

1.3k views Asked by At

After running the program and trying to display the purchase date the program throws an exception here is the code for getters and setters for purchase date:

public void setPurchaseDate(String purchaseDate){
    String[] dateSplit = purchaseDate.split("/");
    int month, day, year;
    month = Integer.parseInt(dateSplit[0]);
    day = Integer.parseInt(dateSplit[1]);
    year = Integer.parseInt(dateSplit[2]);
    GregorianCalendar date = new GregorianCalendar (year, month-1, day);
}

public String getPurchaseDate(){
    String date;
    SimpleDateFormat sdf = new SimpleDateFormat("MM/DD/YYYY");
    date = sdf.format(this.purchaseDate.getTime());
    return date;
}

this the exception from the console:

Exception in thread "main" java.lang.NullPointerException
at jasonsiboleproject5.motorVehicle.getPurchaseDate(motorVehicle.java:88)
at jasonsiboleproject5.car.toString(car.java:69)
at java.lang.String.valueOf(String.java:2847)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at java.util.AbstractCollection.toString(AbstractCollection.java:458)
at java.lang.String.valueOf(String.java:2847)
at java.io.PrintStream.println(PrintStream.java:821)
at jasonsiboleproject5.mainclass.main(mainclass.java:83)

Java Result: 1

1

There are 1 answers

2
Ankur Singhal On BEST ANSWER

1.) First check for the format you have passed, is it valid "MM/DD/YYYY" or use this "MM/dd/yyyy".

2.) Also in your function setPurchaseDate, you have not set the date, and in getter we are calling this.purchaseDate.getTime(), where this.purchaseDate will be null. So first set the value properly and also add a null check.