How do I exit a while loop in Java?

后端 未结 10 2564
情话喂你
情话喂你 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 03:59

    You can do multiple condition logical tests within the while() check using the same rules as within any logical check.

    while ( obj != null ) {  
        // do stuff  
    }
    

    works, as does

    while ( value > 5 && value < 10 ) {  
        // do stuff  
    }  
    

    are valid. The conditionals are checked on each iteration through the loop. As soon as one doesn't match, the while() loop is exited. You can also use break;

    while ( value > 5 ) {  
        if ( value > 10 ) { break; }  
        ...  
    }  
    

提交回复
热议问题