错误"小时无法解决变量",我做错了什么?

时间:2014-10-06 21:47:27

标签: java variables

    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);

这是一个将军事时间转换为标准时间的程序。我不断得到错误“小时无法解决变量”,但不明白我的代码有什么问题。任何洞察力的帮助都会有所帮助。

1 个答案:

答案 0 :(得分:3)

您已在每个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在每种情况下都只被初始化一次,所以它不会抱怨变量可能没有被初始化或者变量在启动后可能已被更改。