Java break nested for

How to break from a nested loop in Java? [Example]

There are situations we need to be nested loops in Java, one loop containing another loop like to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in a two-dimensional array. There are a couple of more situations where you need nesting looping like printing the pascal triangle and printing those star structures exercises from school days. Sometimes depending upon some condition we also like to come out of both inner and outer loops. For example, while searching a number in a two-dimensional array, once you find the number, you want to come out of both loops. The question is how can you break from the nested loop in Java.

You all know about break right? you have seen a break in switch statements, or terminating for, while and do-while loop, but not many Java developers know but there is a feature called a labeled break, which you can use to break from the nested loop.

All the places, where you have used break before is an example of unlabeled break, but once you use a label with the break you can terminate a particular loop in a nested loop structure. In order to use labeled for loop, you first need to label each loop as OUTER or INNER , or whatever you want to call them. Then depending upon which loop you want to exit, you can call break statement as shown in our example.

By the way, there is a better way to do the same thing, by externalizing the code of nested loop into a method and using a return statement for coming out of the loop. This improves the readability of your algorithm by giving an appropriate name to your logic. See Core Java Volume 1 — Fundamentals to learn more about how to use a label with break and continue statements in Java.

How to Break from a Nested Loop in Java using Lable

There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.

This means if you have 10 level of nested loop, you can break from all of them by just calling break and label of first loop. Similarly if you use labeled continue, it starts continuing from the labeled loop.

Читайте также:  Функция round в javascript

This gives Java developer immense power, similar to what goto gives to C programmers, but label in Java is little different then goto . labeled break has no similarity with goto because it don’t allow you to go on a particular line, all you go is outside the loop. labeled continue is little bit similar to goto because it goes to the loop again but not at any arbitrary point, since continue can only be used with loop, effect is limited to the loops only.

By the way, In practice, if you want to exit at any point inside an inner loop then you should better use return statement. For this you need to externalize the code into a method and then call it, now at any point you want to go out of the loop, just call return without any value. This will improve readability.

As I said before, you can also see Core Java Volume 1 — Fundamentals to learn more about how to use a label with break and continue statement in Java.

How to break from nested Loop in Java

Here is the sample code for breaking the nested loop in Java. In this example, we just have two loops, OUTER and INNER. We are a printing number in both the loop but once the product of two counters exceeds 5, we break out from the outer loop.

This makes the program complete because we also come out of the main method. In the next example, the same logic has been developed using a method and return statement called breakFromNestedLoop() , you can see that how much it improve the readability.

So next time if you have to break out from the nested loop consider using a method and return statement over labeled break statement.

import java.io.IOException; /** * How to break from nested loop in Java. You can use labeled * statement with break statement to break from nested loop. * * @author WINDOWS 8 */ public class BreakingFromNestedLoop< public static void main(String args[]) throws IOException < // this is our outer loop outer: for (int i = 0; i < 4; i++) < // this is the inner loop for (int j = 0; j < 4; j++) < // condition to break from nested loop if (i * j > 5) < System.out.println("Breaking from nested loop"); break outer; > System.out.println(i + " " + j); > > System.out.println("exited"); // better way is to encapsulate nested loop in a method // and use return to break from outer loop breakFromNestedLoop(); > /** * You can use return statement to return at any point from a method. * This will help you to break from nested loop as well */ public static void breakFromNestedLoop()< for(int i=0; i6; i++)< for(int j=0; j3; j++)< int product = i*j; if(product > 4)< System.out.println("breaking from nested loop using return"); return; > > > System.out.println("Done"); > > Output 0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 2 0 2 1 2 2 Breaking from nested loop exited breaking from nested loop using return

That’s all about how to break from a nested loop in Java. You have seen that how you can use the label with a break statement to terminate the outer loop from the inner loop, but you can do much better with encapsulating the loop in a method and then using a return statement to break from a nested loop. You can also use a label with a continue statement as well.

Читайте также:  These tags all table tags html

Источник

How to break out of nested loops in Java

Break out of nested loop in java

It is very important to understand how nested loops work to ensure that applying break will output the desired result.

If you are a novice with nested loops, I am going to make the concept as easy as possible for you to understand.

When you apply break in the inner loop, it results in breaking the loop when a specific condition is met, but the outer loop continues to execute.

The following nested loop outputs the result of multiplying the two loops until the outer loop reaches position 3 .

The loop will skip position 3 and continue executing for the remaining positions.

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16

Using named loop

In the first example we discussed, the nested loop continued to execute the outer loop after breaking position 3 .

To prevent the outer loop from continuing to execute, we can use a named loop which is simply a loop with a label .

When the condition is met, instead of just breaking the nested loop, we want to add the named loop to the break statement to ensure that it breaks the outer loop.

For this approach, the nested loop will print out the product of the two loops until the outer loop reaches position 3 .

The break statement will break the outer loop preventing it from iterating further.

Using named block

Block is a sequence of statements containing local classes and variables within braces and can be used to break out of nested loops.

The block executes the statements one by one until the last line of code. If the code executes successfully, the block terminates successfully, and the same case applies if the code terminates abnormally.

To break out of a nested loop using this approach, we will print out the product of the nested loop until a condition is fulfilled.

Once the condition is fulfilled, we will break the execution of the block, which will, in effect, break the execution of the nested loop.

The block will break the nested loop when the product is equal to 4 , and you can also add some statements to be executed if the condition was not valid before the closing braces of the block.

Источник

Разрыв вложенных циклов в Java

Разрыв вложенных циклов в Java

  1. Разорвите внутренний цикл с помощью оператора break в Java
  2. Разорвать вложенный цикл с помощью оператора break с помощью метки в Java
  3. Разорвать вложенный цикл с помощью оператора break в Java
  4. Разорвать вложенный цикл с помощью flag переменной в Java
  5. Разорвать вложенный цикл с помощью оператора return в Java

В этом руководстве представлены способы разбиения вложенных циклов в Java. Мы включили несколько примеров программ, которым вы можете следовать в качестве руководства.

Цикл — это метод, который позволяет нам повторять любой оператор кода любое количество раз в зависимости от заданного условия. Java поддерживает несколько типов циклов, таких как цикл while , цикл do-while , цикл for и цикл for-each . Мы также можем вложить эти петли.

Читайте также:  Http elearning sygroup ru view doc html

В этой статье вы узнаете, как разорвать вложенный цикл в Java. Есть несколько способов разорвать вложенный цикл; они включают использование операторов break и return . Читай дальше, чтобы узнать больше!

Разорвите внутренний цикл с помощью оператора break в Java

Если вы хотите прервать цикл, вы можете использовать оператор break . Этот оператор нарушит внутренний цикл, только если вы примените его во внутреннем цикле. Вот как это сделать:

public class SimpleTesting  public static void main(String[] args)    for (int i = 0; i  5; i++)   for (int j = 0; j  5; j++)   System.out.println(j);  if(i==2)   System.out.println("loop break");  break;  >  >  System.out.println();  >  > > 
0 1 2 3 4  0 1 2 3 4  0 loop break  0 1 2 3 4  0 1 2 3 4 

Разорвать вложенный цикл с помощью оператора break с помощью метки в Java

Если вы хотите разорвать все циклы, как внутренние, так и внешние, вы можете использовать метку с оператором break , который вырезает все циклы и перемещает управление во внешний цикл. См. Пример ниже:

public class SimpleTesting  public static void main(String[] args)   out:  for (int i = 0; i  5; i++)   for (int j = 0; j  5; j++)   System.out.println(j);  if(i==2)   System.out.println("loop break");  break out;  >  >  System.out.println();  >  > > 
0 1 2 3 4  0 1 2 3 4  0 loop break 

Разорвать вложенный цикл с помощью оператора break в Java

Цикл может иметь типы while , for или for-each , и мы можем использовать оператор break в любом из этих циклов. В этом примере мы используем цикл while и прерываем его поток с помощью оператора break . См. Пример ниже:

public class SimpleTesting  public static void main(String[] args)   int i = 0;  out:  while (i5)   int j = 0;  while (j5)   System.out.println(j);  if(i==2)   System.out.println("loop break");  break out;  >  j++;  >  System.out.println();  i++;  >  > > 
0 1 2 3 4  0 1 2 3 4  0 loop break 

Разорвать вложенный цикл с помощью flag переменной в Java

Этот метод представляет другой сценарий, в котором мы используем переменную в условии цикла; когда условие выполнено, цикл прерывается. Этот код хорош, если вы не хотите использовать оператор break . Этот процесс также лучше, потому что он делает код более читабельным. Следуйте блоку кода ниже:

public class SimpleTesting  public static void main(String[] args)   boolean flag = false;  for (int i = 0; i  5 && !flag; i++)   System.out.println(i);  if(i==3)   System.out.println("loop break");  flag = true;  >  >  > > 

Разорвать вложенный цикл с помощью оператора return в Java

Оператор return в Java используется для передачи ответа вызывающему методу. Мы можем использовать оператор return в цикле, чтобы прервать его. Это альтернатива оператору break , но он может работать только в определенных сценариях. См. Пример ниже:

public class SimpleTesting  public static void main(String[] args)   boolean isStop = iterate();  if(isStop)  System.out.println("Loop stop");  else System.out.println("Loop not stop");  >  static boolean iterate()   for (int i = 0; i  5; i++)   for (int j = 0; j  5; j++)   System.out.println(j);  if(i==2)   return true;  >  >  System.out.println();  >  return false;  > > 
0 1 2 3 4  0 1 2 3 4  0 Loop stop 

Сопутствующая статья — Java Loop

Источник

Оцените статью