How do I exit a while loop in Java?

后端 未结 10 2318
情话喂你
情话喂你 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:55

    if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.

    package com.java.demo;
    
    /**
     * @author Ankit Sood Apr 20, 2017
     */
    public class Demo {
    
        /**
         * The main method.
         *
         * @param args
         *            the arguments
         */
        public static void main(String[] args) {
            /* Initialize while loop */
            while (true) {
                /*
                * You have to declare some condition to stop while loop 
    
                * In which situation or condition you want to terminate while loop.
                * conditions like: if(condition){break}, if(var==10){break} etc... 
                */
    
                /* break keyword is for stop while loop */
    
                break;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:59

    Use break:

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

    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) {
        ....
    }
    
    0 讨论(0)
  • 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; }  
        ...  
    }  
    
    0 讨论(0)
  • 2020-11-27 04:00

    break is what you're looking for:

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

    alternatively, restructure your loop:

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

    or:

    do {
        // do stuff
    } while (obj != null);
    
    0 讨论(0)
  • 2020-11-27 04:04

    To exit a while loop, use Break; This will not allow to loop to process any conditions that are placed inside, make sure to have this inside the loop, as you cannot place it outside the loop

    0 讨论(0)
  • 2020-11-27 04:05
    while(obj != null){
      // statements.
    }
    
    0 讨论(0)
提交回复
热议问题