在Java中退出/终止while循环的最佳方式是什么?
例如,我的代码当前如下所示:
while(true){
if(obj == null){
// I need to exit here
}
}发布于 2011-10-31 17:16:14
使用break
while (true) {
....
if (obj == null) {
break;
}
....
}但是,如果代码看起来与您指定的完全相同,则可以使用普通的while循环并将条件更改为obj != null
while (obj != null) {
....
}发布于 2011-10-31 17:17:35
while(obj != null){
// statements.
}发布于 2011-10-31 17:18:11
break就是你要找的东西:
while (true) {
if (obj == null) break;
}或者,重构您的循环:
while (obj != null) {
// do stuff
}或者:
do {
// do stuff
} while (obj != null);https://stackoverflow.com/questions/7951690
复制相似问题