我有上编译这段代码用javac麻烦:“变量可能尚未初始化”即使我确定它是
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的给我上线return year;
的错误“变量“年“可能尚未初始化”。但是因为它是在一个while循环中的,所以我知道它会被初始化。我问我的T.A.对此,他无法回答我为什么会发生这种情况。他最好的猜测是Javac并不是一个很好的编译器,可以用来计算这种东西。
基本上,这个错误为什么会发生?我知道我可以通过在进入while循环之前初始化一年来解决它,但我想知道是否有另一种方法来实现我想要实现的目标。
只是初始化一年'-1' – EpicPandaForce 2014-09-03 14:18:44
有了,你现在有,在“年份”变量尚未初始化,可能无法初始化代码。如果你的while循环不执行会怎么样?只需使用默认值,如-1。 – Marko 2014-09-03 14:21:06
不要为程序流使用catch块。 – Stefan 2014-09-03 14:21:18