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

时间:2018-08-14 01:22:12

标签: java for-loop while-loop operator-precedence variable-declaration

我正在跟踪一个示例,该示例如何在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 循环之外将 result 变量声明为1,怎么办?每次 for 循环运行时,其值是否不会重置为1?对我来说很明显, for 循环在 while 循环接管之前就开始运行,因为运行了 System.out.println()命令每次。 Java的结构允许什么呢?

2 个答案:

答案 0 :(得分:0)


请检查以下内联说明

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

答案 1 :(得分:0)

在for循环的每次迭代中将result重置为1是绝对正确的。确实会重置。

“但是为什么不打印result每次都给我2。”

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:它在第一次迭代中被乘以一次,在第二次迭代中被乘以两次。