Java 注册(整数索引=3;索引-->;1;)
当我执行下面的代码时,我对for循环的执行有疑问Java 注册(整数索引=3;索引-->;1;),java,Java,当我执行下面的代码时,我对for循环的执行有疑问 public class LoopTest { public static void main (String... args) { int num = 3; do { for (int index = 3; index-- > 1;) System.out.print("index value:" + index + "\n");
public class LoopTest
{
public static void main (String... args) {
int num = 3;
do {
for (int index = 3; index-- > 1;)
System.out.print("index value:" + index + "\n");
System.out.print("num:" + num + "\n");
} while (num-- > 1);
System.out.print("num:" + num + "\n");
}
}
输出:
index value:2
index value:1
num:3
index value:2
index value:1
num:2
index value:2
index value:1
num:1
num:0
我完全不明白为什么索引的值是2而不是3,尽管for循环“index-->1”中存在条件,但还是会打印1
期待尽快回复
提前感谢,,
Nusrath.1)您正在递减条件的索引
部分,它甚至在第一次迭代之前执行。这就是为什么在第一次迭代中看到index=2
2) 在条件中使用后缀减量,意思是“减量,但表达式的结果是原始值”,这就是为什么会看到索引=1-当索引为2时,满足条件,但索引减为1
基本上,如果将其写为:
for (int index = 3; index > 1; index--)
我还建议你对你的计划做一个类似的改变
while (num-- > 1)
循环。基本上,混合副作用的操作符和条件几乎总是一个坏主意。这通常会使代码更难阅读和理解,正如这个问题基本上证明的那样
此外,如果在每个for
循环中使用大括号,则肯定会有所帮助。因此,与此相反:
for (int index = 3; index-- > 1;)
System.out.print("index value:" + index + "\n");
写下:
for (int index = 3; index > 1; index--) {
System.out.print("index value:" + index + "\n");
}
我完全不明白索引的值是2而不是3
这是条件通过时迭代的执行顺序:
index = 3;
index--;
System.out.print("index value:" + index + "\n");
index--;
System.out.print("index value:" + index + "\n");
这就是为什么索引值为2和1
可以在循环体内部获得索引
值1的原因是,在该条件下,索引--
返回索引
,然后递减索引
。也许你想要的是:
for (int index = 3; index > 1; index--)
它将到达索引值为3和2的
for
循环的主体。在for
循环中,条件在每个循环之前执行,包括第一个循环。因此,执行顺序是:
int索引=3代码>
索引--代码>
索引>1
2
index-- > 1
该指数下降。
要解决此问题,只需使用默认的for循环:
for(int index = 3; index > 1; index--)
{
... code
}
希望这能解决您的问题。不要使用内联魔法,在现实生活中,它在任何方面都不会有用。只要一条注释,正确缩进代码在您试图理解代码时都会有很大帮助。使用调试器逐行检查每一行代码都是“完全”的好方法了解每行代码的作用。;)