我在 java 循环块的开头放置了一个循环中断,而不是在 loop 关键字之前。这很常见还是会带来意想不到的结果?
I put a loop break in java at the start of loop block and not before the loop keyword. Is that common or would it bring unexpected results?
我将向您展示我提交的作业的答案以给出它的想法
void chkbnch()
{
System.out.println("\n The students under notice period are =>\n\n");
for(int i=0;i<25;i++)
**ol:{**
int cnm=0;
int cnm2=0;
for(int j=0;j<7;j++)
{
if(mrks[i][j]>=50)
{
cnm++;
}
if(cnm==3)
{
//i++;
**break ol;**
}
if(mrks[i][j]<50)
{
cnm2++;
}
}
if(cnm2>=3||cnm<3)
{
System.out.println("\n Student id =>"+(i+1));
}
}
}
当我不希望循环递增并且只是重复循环语句时,我在这里使用 break 。我知道这也可以通过递减循环控制来完成,但这不是我的问题。
我想问的是 java 中定义的这种行为,或者这只是其结果的一种可能性。
您似乎想要 continue 关键字而不是 break。 continue
中断循环的当前迭代,执行跳回到评估阶段,如果评估通过,则循环继续。 break
中断循环的当前迭代,执行跳转到循环结束右大括号后的第一行。
编辑:如果在 continue
循环时需要对 "not increment" 的循环增量控制,例如,在继续后从被循环的列表中拉出相同的对象,然后您需要推出自己的解决方案。
这种 break
语句的使用是完全合法的,尽管它很不寻常,而且它并没有按照你说的去做。
JLS §14.15 说:
A break
statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a switch
, while
, do
, or for
statement.
你例子中的"labeled statement"就是{
..}
块语句,也就是for
循环执行的语句。当您执行 break 时,该块语句完成,returns 控制 for
循环,继续执行增量 i++
,测试条件 i<25
,然后得到继续循环。
它与直接标记外循环,然后使用 continue ol;
.
具有相同的行为
循环计数器仍会递增。如果你想防止这种情况发生,要么用手动 i--;
来抵消它,要么将 i++;
移出 for
循环头并移到循环体的末尾。
我将向您展示我提交的作业的答案以给出它的想法
void chkbnch()
{
System.out.println("\n The students under notice period are =>\n\n");
for(int i=0;i<25;i++)
**ol:{**
int cnm=0;
int cnm2=0;
for(int j=0;j<7;j++)
{
if(mrks[i][j]>=50)
{
cnm++;
}
if(cnm==3)
{
//i++;
**break ol;**
}
if(mrks[i][j]<50)
{
cnm2++;
}
}
if(cnm2>=3||cnm<3)
{
System.out.println("\n Student id =>"+(i+1));
}
}
}
当我不希望循环递增并且只是重复循环语句时,我在这里使用 break 。我知道这也可以通过递减循环控制来完成,但这不是我的问题。
我想问的是 java 中定义的这种行为,或者这只是其结果的一种可能性。
您似乎想要 continue 关键字而不是 break。 continue
中断循环的当前迭代,执行跳回到评估阶段,如果评估通过,则循环继续。 break
中断循环的当前迭代,执行跳转到循环结束右大括号后的第一行。
编辑:如果在 continue
循环时需要对 "not increment" 的循环增量控制,例如,在继续后从被循环的列表中拉出相同的对象,然后您需要推出自己的解决方案。
这种 break
语句的使用是完全合法的,尽管它很不寻常,而且它并没有按照你说的去做。
JLS §14.15 说:
A
break
statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be aswitch
,while
,do
, orfor
statement.
你例子中的"labeled statement"就是{
..}
块语句,也就是for
循环执行的语句。当您执行 break 时,该块语句完成,returns 控制 for
循环,继续执行增量 i++
,测试条件 i<25
,然后得到继续循环。
它与直接标记外循环,然后使用 continue ol;
.
循环计数器仍会递增。如果你想防止这种情况发生,要么用手动 i--;
来抵消它,要么将 i++;
移出 for
循环头并移到循环体的末尾。