首页 > 解决方案 > 嵌套循环中的语法和变量声明:内部声明如何优先?

问题描述

我正在关注如何在 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

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

标签: javafor-loopwhile-loopoperator-precedencevariable-declaration

解决方案



请检查下面的内联解释

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
     }
    }
}

推荐阅读