Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Help with try/catch scope in Java

Name: Anonymous 2012-12-08 17:34

Here's one of my classes:
    public static int secondOfDay()  {
        SimpleDateFormat timeUTC = new SimpleDateFormat("HH:mm:ss");
        timeUTC.setTimeZone(TimeZone.getTimeZone("GMT"));
        SimpleDateFormat dateFormatLocal = new SimpleDateFormat("HH:mm:ss");
        String time;
        int second;
        try {
            time = dateFormatLocal.parse(timeUTC.format(new Date())).toString().substring(11, 19).trim();
        } catch (ParseException e) {
        }
        second = Integer.parseInt(time.substring(0,2)) * 3600 + Integer.parseInt(time.substring(3,5)) * 60 + Integer.parseInt(time.substring(6,8));
        return second;
    }


For some reason, time.substring states that "The local variable time may not have been initialized", and it definitely has something to do with the scope in the try/catch. the issue is, I've declared time outside of the try/catch, and I have no idea how to fix this, because it looks like it should work.
Any help?

Thanks.

Name: Anonymous 2012-12-08 17:46

Do String time = null on the top.

Name: Anonymous 2012-12-08 17:55

>>2
Nurupo!

Name: Anonymous 2012-12-08 17:56

Yeah. >>2. Initialise time, then it will have been initialised.

Name: Anonymous 2012-12-08 18:40

You should be doing the second = within the try, and returning -1 or throwing an exception within the catch.

The reason it might not be initialised is the reason it has to be in the try...catch: if the date-format stuff fails, time won't be assigned a value.

It looks like you just blindly added the try...catch to shut the compiler up without actually thinking about what you were doing.

Name: Anonymous 2012-12-08 19:03

>>5
There's no way the dateFormatLocal.parse could fail though.

Name: Anonymous 2012-12-08 19:15

Couldn't you just copy the code from firstOfDay?

Name: Anonymous 2012-12-08 19:24

Why are you HELPING HIM?

Don't change these.
Name: Email:
Entire Thread Thread List