如何在Java中退出while循环? [英] How do I exit a while loop in Java?

查看:177
本文介绍了如何在Java中退出while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中退出/终止while循环的最佳方法是什么?

What is the best way to exit/terminate a while loop in Java?

例如,我的代码目前如下:

For example, my code is currently as follows:

while(true){
    if(obj == null){

        // I need to exit here

    }
}


推荐答案

使用 break

while (true) {
    ....
    if (obj == null) {
        break;
    }
    ....
}






但是,如果您的代码看起来完全,就像您指定的那样,您可以使用正常的循环并更改条件到 obj!= null


However, if your code looks exactly like you have specified you can use a normal while loop and change the condition to obj != null:

while (obj != null) {
    ....
}

这篇关于如何在Java中退出while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆