有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么“i”和“i”在Java for循环中有相同的行为?

为什么在Java中,i----ifor循环中有相同的行为

例: 我的变量“i”在循环之前不会减少:

for(int i = 5; i > 0; --i) {
    System.out.println(i);
}

for(int i = 5; i > 0; i--) {
    System.out.println(i);
}

。。。将同时打印5,4,3,2,1

但是:

int i = 5;
System.out.println(--i);


int i = 5;
System.out.println(i--);

。。。将打印4和5


共 (2) 个答案

  1. # 1 楼答案

    这是因为for循环是这样工作的:

    for (<1. variable declaration and initialization>;
         <2. condition to loop>;
         <4. for update>) {
        <3. statements>
    }
    

    在执行for循环中的语句之后,在检查要循环的条件之前,执行i----i条件。也就是说,在更新部分中使用i----i并不重要

  2. # 2 楼答案

    因为循环是这样工作的:

    for(<Part that will be executed before the loop>;
        <Part that is the condition of the loop>;
        <Part that will be executed at the end of each iteration) {
        <statements>
    }
    

    因此,任何for循环都可以这样重写:

    <Part that will be executed before the loop>
    while(<Part that is the condition of the loop>) {
        <statements>
        <Part that will be executed at the end of each iteration>
    }
    

    用你的例子来做这件事会导致:

    int i = 5; // Part that will be executed before the loop
    while(i > 0) { // Part that is the condition of the loop
        System.out.println(i); // statements
        --i; // Part that will be executed at the end of each iteration
    }
    

    正如您所看到的,无论输出是--i还是i--都与此无关,因为print调用总是在变量递减之前发生。为了达到你想要的效果,你可以尝试以下方法:

    int i = 5;
    while(i > 0) {
        --i;
        System.out.println(i);
    }