java - 错误 "hours cannot be resolved to a variable",我做错了什么?

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

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

最佳答案

您已在每个 if case block 中声明了 hours,但由于 block 立即结束,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 在每种情况下都被初始化一次,因此它不会提示该变量可能不会已经初始化或者变量在初始化后可能已被更改。

关于java - 错误 "hours cannot be resolved to a variable",我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225406/

相关文章:

java - org.postgresql.util.PSQLException : ERROR: column "geo_detail" is of type point but expression is of type bytea any solution please?

javascript - 将变量整数传递给jquery函数?

mysql - 在 MySQL 中创建 ENUM 变量类型

java - 我可以在Java中使用listiterator来访问随机位置的元素吗?

java - 如何在Jpanel上绘画?

java - 如何显示 jsp 来响应对 servlet 的 ajax 调用

java - (k<<24)>>>24在遥感图像读取中有何意义?

php - Yii 2 : Can I access a variable in a view that's rendered by another view?

javascript - 最佳实践 "OR"和 "Ternary"运算符

javascript - 如何从 javascript 刷新 php 中的值?