for循环中的更新表达式未编译

update expression in for loop is not compiling

为什么下面的循环没有编译

for(int i=1,j=3;i<3; while(j-->=0) {System.out.println(j);},i++  );

这是因为 java 不允许在更新表达式中使用除 increment 之外的任何其他语句...

根据 oracle 文档

for (initialization; termination;
     increment) {
    statement(s)
}

使用此版本的 for 语句时,请记住:

初始化表达式初始化循环;它在循环开始时执行一次。 当终止表达式的计算结果为假时,循环终止。 增量表达式在循环的每次迭代后被调用;这个表达式增加或减少一个值是完全可以接受的。

第三个参数应该是一个increment/decrment值

这是错误的语法 for(int i=1,j=3;i<3; while(j-->=0)for loop 是一种不同的循环机制,while 也可以认为是它的对应物。

但是 while 而不是 for 中的 increment 部分甚至无法编译。

尝试这样做:-

for(int i = 1, j = 3; i < 3 && j-- >= 0; i++) {
    System.out.println(j);
}

while(j>=0){ // whatever your condition
 System.out.println(j); //your logic here
 j--; // increment/decrement
}

找到for here and while here

的官方文档
for(int i = 1, j = 3; i < 3 && j-- >= 0; i++) {
    System.out.println(j);
}

喜欢吗?

The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

Basic for Statement:

for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

for循环有语法,不能这样写

首先初始化:

i = 1, j = 3

然后是条件:

i < 3 && j >= 0

然后是 inc/dec 或更新变量:

i++, j--

for(int i=1, j=3; i<3 && j >=0; i++, j--)
{
System.out.println(j);
}

OP 想做的事情实际上是可能的。问题是,increment expression 只能是一个表达式。它不一定是递增的。它可以是任何表达式。以下代码编译:

private static void innerLoop(int i, int j){
    while(j-->=0) {
        System.out.println(j);
    }
}

public static void main (String[] args) throws java.lang.Exception
{
    for(int i=1,j=3;i<3;innerLoop(i++,j));
}

编辑 现在,"single expression" 术语并不像我想象的那么简单明了,因为还可以编译以下代码:

private static void innerLoop(int j){
    while(j-->=0) {
        System.out.println(j);
    }
}

...

for(int i=1,j=3;i<3;innerLoop(j), i++);

进一步阅读后,我猜测 增量表达式 不能有直接的 control flow statement。通过将控制流语句隐藏在函数中来避免控制流语句效果很好。