Giving name to a loop

前端 未结 6 1770
北荒
北荒 2020-12-06 05:33

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:
          


        
相关标签:
6条回答
  • 2020-12-06 05:37

    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.

    0 讨论(0)
  • 2020-12-06 05:41

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

    0 讨论(0)
  • 2020-12-06 05:42

    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.

    0 讨论(0)
  • 2020-12-06 05:44
    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).

    0 讨论(0)
  • 2020-12-06 05:49

    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.

    0 讨论(0)
  • 2020-12-06 06:01

    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.

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