In Java, how does break interact with nested loops?

后端 未结 4 2096
攒了一身酷
攒了一身酷 2020-12-23 21:32

I know a break statement jumps out of a loop, but does it jump out of nested loops or just the one its currently in?

4条回答
  •  攒了一身酷
    2020-12-23 22:11

    You can also break out by using Exceptions, so you can handle multiple reasons

     void fkt1() {
        try {
            while (true)
                fkt2();
        } catch (YourAbortException e) {
            e.printStackTrace();
        }
    
        //go on
    }
    
    void fkt2() {
        while (true)
            if (abort)
                throw new YourAbortException();
    }
    

提交回复
热议问题