Giving name to a loop

2020-02-05 12:52发布

While browsing questions and answers in this forum i found a piece of code were names were given to loops in order to use them for break. Like

nameofloop:
    for(){
        for(){
             if(){ break nameofloop;}
        }
    }

Im new to programming and i havent seen that before. My question is what other uses of naming loops are there?

标签: java loops
6条回答
小情绪 Triste *
2楼-- · 2020-02-05 13:28

This is not a labeled loop, is just a label that you place anywhere and then you can "break" or "continue" to depending on your conditions. You can also use in a nested if-else with for loopings in order to break several loops decorated with if-else, so you can avoid setting lot of flags and testing them in the if-else in order to continue or not in this nested level.

Its use is discouraged as resembles a goto and causes spaghetti-code.

Personally I used only once, time ago, in order to break a for loop inside other two for loops with if-else and continue in the outer loop, as break inside a loop breaks this loop, but you continue in the outer loop, not the most-outer that was my case.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-05 13:33

Officially, I believe this is called a "labeled break". It's useful for breaking out of nested loops, such as:

found:
    for (int i = 0; i < 100; i++)
        for (int j = 0; j < 100; i++)
            if ( /* Some condition is met */)
                break found;

I don't think it's useful for anything else.

查看更多
4楼-- · 2020-02-05 13:34

I think it's the only case it's used. And it's not something which is commonly used, because it's usually more readable to change the value of a flag to end a loop prematurely.

查看更多
5楼-- · 2020-02-05 13:40
  1. Create an array (int) of size 10.

  2. Let the user assign the values - (use for-loop).

  3. Find the total and average of the values stored in the array - (use for- loop).

查看更多
Lonely孤独者°
6楼-- · 2020-02-05 13:40

It's known as a labelled break which is a form of branching statement. You can see all the examples in the Official Documention.

查看更多
Viruses.
7楼-- · 2020-02-05 13:42

You can also say:

continue nameofloop;

...to jump to start of the named loop. I don't think there are any other use cases for labels in Java.

查看更多
登录 后发表回答