Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try catch returning null

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;
}
like image 899
Zabava Mihai Avatar asked Mar 25 '26 17:03

Zabava Mihai


1 Answers

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;
    }
like image 55
maddy Avatar answered Mar 27 '26 05:03

maddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!