I am trying to make this code run properly. If I enter a date of birth wrong first, the program returns me null, if I enter the dob correctly from the first time it returns the correct dob. What I am doing wrong?
public static Date convertDOB() { //Date of Birth Method
System.out.println("Enter Date Of Birth: ");
String dob = in.nextLine();
SimpleDateFormat formater = new SimpleDateFormat("dd/MM/yyyy");
Date realdob = null;
try {
realdob = formater.parse(dob);
} catch (ParseException e) {
System.out.println("In-correct format. Format should be dd/mm/yyyy");
convertDOB();
}
return realdob;
}
You are initialising a new object of type Date during every recursive call. So even in subsequent recursive calls of the method, if the correct DOB is present, the first call of the method always returns null, since that's what was initialised. Instead in the catch block return the DOB you are getting from the very next call-
public static Date convertDOB() //Date of Birth Method
{
System.out.println("Enter Date Of Birth: ");
String dob = in.nextLine();
SimpleDateFormat formater = new SimpleDateFormat("dd/MM/yyyy");
Date realdob = null;
try
{
realdob = formater.parse(dob);
}
catch(ParseException e)
{
System.out.println("In-correct format. Format should be dd/mm/yyyy");
return convertDOB();
}
return realdob;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With