java - 为什么这段代码不起作用?它给我一个错误 "variable h might not have been initialized"

标签 java

以下代码未通过编译。 它给了我这个错误:

variable h might not have been initialized

public class MnmEx {

    public static void main(String[] args) {
        
        int h; 
        for (int i = 0; i < 50; i++) {
            for (int j = 0; j < 50; j++) {
                if (j == 10) {
                    h = 20; 
                }
            }
        }
        System.out.println(h); 
    }
}

最佳答案

编译器不会分析您的 for 循环以确保 h 始终在其中分配。因此,它不知道在您尝试打印 h (System.out.println(h)) 时,它是否已被分配。

通过给 h 一个初始值可以轻松避免这种情况:

int h = 0;

关于java - 为什么这段代码不起作用?它给我一个错误 "variable h might not have been initialized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70692066/

相关文章:

java - Joda:将系统日期和时间转换为另一个区域中的日期/时间

java - 覆盖示例的问题

java - 了解家庭作业

java - 如何打印自己实现的堆栈?

java - 为什么两个同名的字符串有相同的对象实例?

java - 破解编码面试 : Why does the recursive subset algorithm increase the index rather than decreasing it?

java - 未找到提供程序 com.sun.xml.rpc.client.ServiceFactoryImpl

java - 使 BufferedImage 中的黑色像素变亮

java - 如何控制 okHttpClient 的连接大小?

java - Lombok 和 jackson - 冲突/不明确的属性名称定义