嵌套循环中的语法和变量声明:内部声明如何优先?

Syntax and Variable Declaration in Nested Loops: How Does an Inner Declaration take Precedence?

我正在关注如何在 java 中生成脚本的示例,该脚本计算并打印 2 的幂(2、4、8、16...),脚本如下所示:

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

     int e;
     int result;

     for(int i = 1; i < 10; i++) {
     result = 1; //why doesn't this reset result to 1 for every iteration?
     e = i;
        while(e > 0) {
        result *= 2;
        e --;
        }

        System.out.println("2 to the " + i + " power is " + result);
        //I would expect printing "result" here would result in 2 every time...
     }
    }
}

输出为:

2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512

我的问题是,如果 result 变量在初始 for 循环中但在内部 while循环,为什么每次for循环运行时它的值都不会重置为1?我很清楚 for 循环在 while 循环接管之前开始 运行ning,因为 System.out.println()命令每次都是运行。 Java 的结构允许这样做的原因是什么?


请查看下面的内联解释

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

     int e;
     int result;

     for(int i = 1; i < 10; i++) {
     result = 1; //why doesn't this reset result to 1 for every iteration?
                // Yes , result will be 1 always here, you can print the result variable before while as below
     // System.out.println("Result : " + result);
     e = i;
        while(e > 0) {
        result *= 2;
        e --;
        }

        System.out.println("2 to the " + i + " power is " + result);
        //I would expect printing "result" here would result in 2 every time...
        // here the value of result will be decided based on e, here we are multiplying result with 2 , "e" no.of times
     }
    }
}

关于在 for 循环的每次迭代中将 result 重置为 1,你是完全正确的。它确实会重置。

"But why doesn't printing result give me 2 every time"你问。

result 被设置为 1 之后,在 for 循环的迭代结束之前,while 循环运行。 while 循环运行了多少次?这取决于 i。在 for 循环的第一次迭代中,while 循环循环一次,在 for 循环的第二次迭代中,while 循环循环两次,在 for 循环的第三次迭代中,while 循环循环三次,依此类推。

在 for 循环的每次迭代结束时,result 将包含 2 的 <however many times the while loop looped for> 次方的值。所以在 for 循环的第一次迭代结束时,result 是 2 因为 while 循环只循环了一次。在第二次迭代结束时,result 是 4,因为 while 循环 运行 两次,所以 result *= 2 是 运行 两次。

如果 result 没有被重置,它会在 for 循环的第二次迭代结束时变为 8:它在第一次迭代中乘以一次,在第二次迭代中乘以两次。