I am having trouble with Javac on compiling this piece of code:
public static int getYear() {
Console input = System.console();
Boolean gotYear = false;
int year;
String userInput = input.readLine();
while (!gotYear) {
try {
year = Integer.parseInt(userInput);
gotYear = true;
} catch (Exception e) {
System.out.print("Please insert a valid date. ");
userInput = input.readLine();
}
}
return year;
}
Javac gives me the error on line return year;
that "variable 'year' might not have been initialized". But since it's inside a while loop, I know for sure it will have been initialized. I asked my T.A. about this and he was not able to answer me why this happens. His best guess is that Javac is not a very good compiler for figuring this kind of stuff out.
Basically, why is this error happening? I know I can fix it by initializing year before I enter the while loop, but I wanted to know if there is another way of achieving what I'm trying to achieve.
No. You have to initialize. Local aka method variables must gets initialized before they use.
Local variable won't get default values. You have to initialize them, before you use.
Your year variable is initialized in a try block. It's obvious to us that it won't get out the loop until something OK is input. But the compiler's rules are simpler than that : as the initialisation can be disrupted by an exception, it considers that year may be uninitialized.
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