"the variable may not have been initialized" although I'm pretty sure it is
I am having problems with Javac while 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 is giving me an error on the line return year;
that "the variable" year "may not have been initialized". But since it is inside a while loop, I know for sure that it will be initialized. I asked T. about this and he could not answer me why this is happening. His best guess is that Javac is not a very good compiler for understanding what it is.
Basically why is this error happening? I know I can fix this by initializing the year before I step into the while loop, but I wanted to know if there is another way to achieve what I am trying to achieve.
source to share
Imagine a situation where gotYear in
while (!gotYear)
evaluates to true .
In this case, year will not be initialized as it is inside a while loop.
while (!gotYear) {
try {
year = Integer.parseInt(userInput);
gotYear = true;
} catch (Exception e) {
System.out.print("Please insert a valid date. ");
userInput = input.readLine();
}
}
At compile time, the java compiler does not evaluate expressions. Therefore gotYear can take one of two values true or false .
Local variables must be initialized in the same scope in which they are declared. Internalization should be done before using it.
source to share
Local variables are used primarily for intermediate calculations, while instance variables are supposed to carry data for calculations for both the future and the intermediate. Java allows default values ββfor instance variables, but local variables need to be assigned a value. Therefore, to avoid errors, you need to initialize local variables.
source to share
year
will not be assigned when it Integer.parseInt(userInput);
throws a NumberFormatException.
What gotYear
then remains a boolean .FALSE while storing in a loop is too complicated for the compiler. He thinks that you will somehow get out of the loop.
The following should behave better.
for (;;) {
try {
year = Integer.parseInt(userInput);
break;
} catch (Exception e) {
System.out.print("Please insert a valid date. ");
userInput = input.readLine();
}
}
Perhaps the compiler can simply accept:
for (boolean keepAsking = true; keepAsking; ) {
try {
year = Integer.parseInt(userInput);
keepAsking = false;
BTW is better to use boolean
instead of object wrapper class boolean
.
source to share