gpt4 book ai didi

java - 在 Java 中,什么时候 "do while"循环是唯一的选择?

转载 作者:行者123 更新时间:2023-12-02 09:14:04 25 4
gpt4 key购买 nike

是否存在必须使用do while循环的情况?这是一种公认​​的做法吗?它似乎相当于一个普通的 while 循环,只不过它的第一次迭代发生在检查条件之前(如果条件成立的话)。

int i = 3;
while ( i > 0 ) { // runs 3 times
i--;
}

对比

int j = 3;
do {
j --;
} while ( j > 0 ); // runs 3 times

一样吗?

编辑:我看过java文档,但是java 文档中的示例看起来并不要求 do while 循环内的特定例程必须在 do while 循环中运行,而不是在常规 while 循环内运行!

最佳答案

Is there ever a situation where you must use a do while loop?

否:每个 do-while 循环都可以通过运行主体来编写为 while 循环在循环开始之前一次。但是,在某些情况下,使用 do-while 构造确实更有意义(即,如果您总是希望循环至少迭代一次),这就是为什么它首先存在。

Is it an accepted practice?

如果你使用得当,那么绝对可以。

It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.

没错。您可以在 tutorial 中阅读有关 do-while 的更多信息。 .

关于java - 在 Java 中,什么时候 "do while"循环是唯一的选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18660955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com