英文:
Is there a "do-for" loop in java?
问题
有没有一个循环,在执行代码块之后检查条件,而不是之前?我想要的是类似于do-while循环的东西。这种语法/功能是否存在?
(是的,我知道我可以在其他地方编写参数并使用do-while循环,我只是好奇。)
英文:
I was wondering if there is a for loop that checks the condition after the code block is executed, rather than before. What I'm looking for is something similar to a do-while loop. Does this syntax/function exist?
(Yes I am aware that I can just write parameters elsewhere and use a do-while loop, I'm just curious.)
答案1
得分: 2
不,它不存在。有什么意义呢?
考虑以下:
do {
...
} for (int j=0; j<2; j++);
-
j
在循环体内不可用。 -
循环条件表示要循环两次,但实际上循环会执行3次。
我们可以解决第一个问题:
int j = 0;
do {
...
} for (; j<2; j++);
但for
循环已经变得无效。它仍然会导致循环运行的次数不明确。在这一点上,你最好使用以下方式:
int j = 0;
do {
…
j++;
} while (j<2); // 或者3,取决于你的需求
甚至可以这样:
```java
int j = 0;
do {
…
} while (++j<2);
英文:
No, it does not exist. What would be the point?
Consider
do {
...
} for (int j=0; j<2; j++);
-
j
is not available inside the loop body -
The loop condition says loop twice, but the loop will execute 3 times.
We can address the first point:
int j = 0;
do {
...
} for (; j<2; j++);
but the for
loop is already emasculated. It still suffers from obscuring the number of times the loop runs. At this point you're better off with
int j = 0;
do {
…
j++;
} while (j<2); // or 3, depending on what you want
or even
int j = 0;
do {
…
} while (++j<2);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论