确实在继续工作吗?

mrb*_*lah 22 java loops do-while

我有一个看起来像:

User user = userDao.Get(1);

do
{
 // processing


 // get the next user
 //
 user = UserDao.GetNext(user.Id);

 if(user == null)
       continue;   // will this work?????????????
}
while ( user != null)
Run Code Online (Sandbox Code Playgroud)

如果它确实有效,它会转到do语句的顶部,而user是null,所以事情会破坏?

也许我应该将循环重写为while语句?

hel*_*ios 36

继续使它跳转到botton处的评估,因此程序可以评估是否必须继续进行另一次迭代或退出.在这种情况下,它将退出.

这是规范:http://java.sun.com/docs/books/jls/third_edition/html/statements.html#6045

您可以在Java语言规范中搜索这些语言问题:http://java.sun.com/docs/books/jls/


Ric*_*ams 5

是的,continue将在 do..while 循环中工作。

您可能想要使用break而不是continue停止处理用户,或者完全删除该if null continue位,因为无论如何,只要 user 为空, while 循环就会中断。


Jam*_*dle 5

这确实不是编写这段代码的最佳方式。如果 user 为 null,那么当您下次尝试获取 user.id 时,您将收到 NullPointerException。更好的方法是:

User user = UserDao.Get(1);
while(user != null) {
  // do something with the user
  user = UserDao.GetNext(user.id);
}
Run Code Online (Sandbox Code Playgroud)