How do I exit a while loop in Java?

后端 未结 10 2319
情话喂你
情话喂你 2020-11-27 03:50

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){

                


        
相关标签:
10条回答
  • 2020-11-27 04:06

    Finding a while...do construct with while(true) in my code would make my eyes bleed. Use a standard while loop instead:

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

    And take a look at the link Yacoby provided in his answer, and this one too. Seriously.

    The while and do-while Statements

    0 讨论(0)
  • 2020-11-27 04:07

    You can use "break" to break the loop, which will not allow the loop to process more conditions

    0 讨论(0)
  • 2020-11-27 04:08

    Take a look at the Java™ Tutorials by Oracle.

    But basically, as dacwe said, use break.

    If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.

    0 讨论(0)
  • 2020-11-27 04:12

    You can use "break", already mentioned in the answers above. If you need to return some values. You can use "return" like the code below:

     while(true){
           if(some condition){
                do something;
                return;}
            else{
                do something;
                return;}
                }
    

    in this case, this while is in under a method which is returning some kind of values.

    0 讨论(0)
提交回复
热议问题