什么时候循环比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语句(也就是强制do语句至少运行一次)后检查while条件的意义。
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 */ );
这篇关于什么时候循环比while循环更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!