首页 > 解决方案 > 如果在主方法中完成声明并在循环内初始化,则在 Java 中无法从 For 循环外部访问变量吗?

问题描述

class Myclass {
    public static void main(String[] args) {

        int x; // Declared in main method

        if (true) {
            for (int i = 0; i < 5; i++) {
                x = 5;// initialized inside loop
            }
        }

        System.out.println(x);// accessing outside for loop
    }
}

这给出了一个错误:变量 x 可能没有被初始化 System.out.println(x); ^ 1 个错误;

但是,下面的代码工作正常

class Myclass {
    public static void main(String[] args) {

        int x; // Declared in main method

        if (true) {
            x = 5;// initialized in if block
            for (int i = 0; i < 5; i++) {
                // x=5;
            }
        }

        System.out.println(x);// accessing outside if loop
    }
}

在这两个代码中,唯一的区别是在第一种情况下,变量在“for循环”中初始化,而在第二种情况下,它在“if块”中初始化。那么为什么它会有所作为。请向我解释,因为我无法找到真正的原因。

标签: javafor-loopcompiler-errorsinitializationdeclaration

解决方案


问题是编译器不知道当你访问它时x 被初始化。那是因为编译器不会检查循环体是否会实际执行(在极少数情况下,即使是这样一个简单的循环也可能不会运行)。

如果条件不总是为真,即如果您使用这样的布尔变量,您的 if 块也是如此:

int x;

boolean cond = true;
if( cond ) {
  x = 5;
}

//The compiler will complain here as well, as it is not guaranteed that "x = 5" will run
System.out.println(x);

您作为人类会说“但cond已初始化true并且永远不会更改”,但编译器不确定(例如,由于可能的线程问题),因此它会抱怨。如果您要创建cond一个最终变量,那么编译器将知道cond在初始化后不允许更改该变量,因此编译器可以内联代码以if(true)再次有效地拥有。


推荐阅读