[英]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);
这是将军事时间转换为标准时间的程序。 我不断收到错误“小时数无法解析为变量”,但不了解我的代码出了什么问题。 任何有见识的帮助都会有所帮助。
您已经在每个if
case块中声明了hours
,但是由于该块立即结束,因此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
仅初始化一次,因此它不会抱怨该变量可能尚未初始化或在初始化后可能已对其进行了更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.