什么时候 do-while 循环比 while 循环更好? [英] When would a do-while loop be the better than a while-loop?
问题描述
这是一个非常主观的问题,所以我会更具体.有没有什么时候 do-while 循环会比普通的 while 循环更好的编码风格?
This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?
例如
int count = 0;
do {
System.out.println("Welcome to Java");
count++;
} while (count < 10);`
在评估 do 语句后检查 while 条件似乎没有意义(也就是强制 do 语句至少运行一次).
It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).
对于像我上面的例子这样简单的事情,我会想象:
For something simple like my above example, I would imagine that:
int count = 0;
while(count < 10) {
System.out.println("Welcome to Java"); count++;
}
通常会被认为是用更好的写作风格写的.
would be generally considered to have been written in a better writing style.
谁能为我提供一个工作示例,说明何时将 do-while 循环视为唯一/最佳选择?你的代码中有 do-while 循环吗?它扮演什么角色,为什么选择 do-while 循环?
Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?
(我有一种预感,do-while 循环可能在游戏编码中有用.如果我错了,请纠正我,游戏开发者!)
(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)
推荐答案
如果要从网络套接字读取数据直到找到字符序列,首先需要读取数据,然后检查数据是否有转义序列.
If you want to read data from a network socket until a character sequence is found, you first need to read the data and then check the data for the escape sequence.
do
{
// read data
} while ( /* data is not escape sequence */ );
这篇关于什么时候 do-while 循环比 while 循环更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!