在Java中是否有一个 “do-for” 循环?

huangapple go评论57阅读模式
英文:

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++);
  1. j 在循环体内不可用。

  2. 循环条件表示要循环两次,但实际上循环会执行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++);
  1. j is not available inside the loop body

  2. 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);  

huangapple
  • 本文由 发表于 2020年8月7日 06:43:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63292755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定