Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't read variable inside try catch

String selectedDate = "2012-" + createdMonth
        + "-" + createdDay;

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");

try {
    Date createdDate = dateFormat.parse(selectedDate);
} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

int x = JOptionPane.showOptionDialog(frame,
    "Here is your new booking schedule:\n "
        + "Timeslot: "
        + selectedTimeslot + "\n"
        + "Date: " + createdDate + "\n"
        + "Continue?",
    "Booking Confirmation",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE, null,
    options, options[1]);

The problem is that createdDate in the JOptionPane can't be resolved to a variable. why is that? I've tried everything like initializing the Date object outside the try catch but it still doesn't work. Help!

like image 782
Blaiz Avatar asked Dec 11 '25 14:12

Blaiz


2 Answers

Because the variable is out of scope once the try block is completed. Move you jOptionPane code to inside the try block or move the createDate declaration outside the try block.

like image 178
OldProgrammer Avatar answered Dec 14 '25 04:12

OldProgrammer


You're defining the variable inside the try-catch block, which is its own scope. Outside the try block, the variable is 'out of scope', so 'doesnt exist' at the later point.

like image 21
akaIDIOT Avatar answered Dec 14 '25 04:12

akaIDIOT



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!