for 循环导致无限循环,当使用 post 增量时
for loop resulting in infinite loop, when post increment is used
我是 java 的新手。需要帮助来分析下面的一小段代码。下面的代码将 'i' 的值始终打印为 0。似乎 'i' 永远不会递增,低于 for 循环会导致无限循环。有人可以解释为什么 'i' 根本没有增加吗?我知道当使用 post 递增运算符时,首先使用表达式值,然后递增该值。因此,循环的第一次迭代会将 'i' 的值打印为 0。但是,至少在第二次迭代中,'i' 应该递增到 1,依此类推。对吗?:
public class PostIncExample {
public static void main(String[] args) {
for(int i=0; i<10;){
System.out.println(i);
i=i++;
System.out.println("hi" + i);
}
}
}
在您的代码中,i++
returns i
的 "old" 值(递增之前的值)。然后将这个旧值分配给 i
。所以在 i = i++
之后,i
和之前的值一样。
++i increments and then uses the variable.
i++ uses and then increments the variable.
Thats why above code always print 0 and goes infinite
您可以修改您的代码如下:
public class PostIncExample {
public static void main(String[] args) {
for(int i=0; i<10;){
System.out.println(i);
i=++i;
System.out.println("hi" + i);
}
}
}
PRE-increment is used when you want to use the incremented value of
the variable in that expression.
POST-increment uses the
original value before incrementing it.
我是 java 的新手。需要帮助来分析下面的一小段代码。下面的代码将 'i' 的值始终打印为 0。似乎 'i' 永远不会递增,低于 for 循环会导致无限循环。有人可以解释为什么 'i' 根本没有增加吗?我知道当使用 post 递增运算符时,首先使用表达式值,然后递增该值。因此,循环的第一次迭代会将 'i' 的值打印为 0。但是,至少在第二次迭代中,'i' 应该递增到 1,依此类推。对吗?:
public class PostIncExample {
public static void main(String[] args) {
for(int i=0; i<10;){
System.out.println(i);
i=i++;
System.out.println("hi" + i);
}
}
}
在您的代码中,i++
returns i
的 "old" 值(递增之前的值)。然后将这个旧值分配给 i
。所以在 i = i++
之后,i
和之前的值一样。
++i increments and then uses the variable.
i++ uses and then increments the variable.
Thats why above code always print 0 and goes infinite
您可以修改您的代码如下:
public class PostIncExample {
public static void main(String[] args) {
for(int i=0; i<10;){
System.out.println(i);
i=++i;
System.out.println("hi" + i);
}
}
}
PRE-increment is used when you want to use the incremented value of the variable in that expression.
POST-increment uses the original value before incrementing it.