提问人:zebra14420 提问时间:10/7/2014 更新时间:10/7/2014 访问量:124
错误“小时无法解析为变量”,我做错了什么?
Error "hours cannot be resolved to a variable", what am I doing wrong?
问:
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a military time: ");
int time = kb.nextInt();
int minutes = (time%100);
if (time < 1){
System.out.println("Illegal time, please give another one.");
}else if (time%100>59){
System.out.println("Illegal time, please give another one.");
}else if (time>2400){
System.out.println("Illegal time, please give another one.");
}else{
if (time<100){
final int hours = 12;
}else if (time<1300){
final int hours = (time/100);
}else{
final int hours = ((time/100)-12); }
if (minutes<10)
System.out.println("Standard time is: "+hours+":0"+minutes);
else if (minutes>=10)
System.out.println("Standard time is: "+hours+":"+minutes);
这是一个将军事时间转换为标准时间的程序。我不断收到错误“小时无法解析为变量”,但不明白我的代码出了什么问题。任何洞察力的帮助都会有所帮助。
答:
3赞
rgettman
10/7/2014
#1
您已在每个案例块中声明,但由于该块立即结束,因此立即超出范围。hours
if
hours
在 之前声明它,以便它保持在您需要的范围内。if
final int hours; // Not initialized yet.
if (time<100){
hours = 12;
}else if (time<1300){
hours = (time/100);
}else{
hours = ((time/100)-12); }
// Now it's still in scope here:
if (minutes<10)
System.out.println("Standard time is: "+hours+":0"+minutes);
else if (minutes>=10)
System.out.println("Standard time is: "+hours+":"+minutes);
请注意,编译器足够聪明,可以确定变量在每种情况下都只初始化一次,因此它不会抱怨变量可能未初始化,或者变量在初始化后可能已更改。final
hours
评论
hours
当您尝试将其打印到控制台时,它不再在范围内。在已声明和 .time
minutes