如果在主方法和循环内初始化中完成声明,则在 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 块”中初始化。那么为什么它会有所作为。请向我解释,因为我无法找到真正的原因。


慕桂英546537
浏览 258回答 3
3回答

HUH函数

问题是编译器不知道当你访问它时x 会被初始化。那是因为编译器不会检查循环体是否真的会被执行(在极少数情况下,即使是这样一个简单的循环也可能不会运行)。如果条件不总是正确的,那么你的 if-block 也是如此,即如果你使用这样的布尔变量:int x;boolean cond = true;if( cond ) {&nbsp; x = 5;}//The compiler will complain here as well, as it is not guaranteed that "x = 5" will runSystem.out.println(x);你作为一个人会说“但cond被初始化true并且永远不会改变”但编译器不确定(例如,因为可能的线程问题),因此它会抱怨。如果你创建cond一个 final 变量,那么编译器会知道cond在初始化后不允许更改,因此编译器可以内联代码以if(true)再次有效地拥有。

繁花如伊

如果您将 if 块中的条件从trueto更改为,false您将得到与variable 'x' might not have been initialized. 当你这样做时if(true),编译器可以理解 if 块中的代码将始终运行,因此变量 x 将始终被初始化。但是当您在 for 循环中初始化变量时,可能会发生 for 循环永远不会运行并且变量未初始化的情况。&nbsp;public static void main(String[] args) {&nbsp; &nbsp; &nbsp; int x; // Declared in main method&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(false)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x=5; //compile error&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<5;i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //x=5 initialized inside loop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(x);&nbsp; &nbsp; &nbsp; &nbsp; }为避免这种情况,将变量初始化为 int x = 0;

慕村225694

它仍然可以访问,但程序可能永远不会访问 for 块。由于编译器不满足 for 循环之外的任何其他 var 初始化,它会给你一个错误。为了编译它,您必须使用默认值初始化变量:class Myclass {&nbsp; &nbsp; public static void main (String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; int x = 0; // Declared in main method and init with a default value.&nbsp; &nbsp; &nbsp; &nbsp; if(true) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<5;i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x=5;// Reinitialized inside loop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(x); // No problems here.&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java