How to break out of nested loops in Java?
Hi everyone! I'm new to Java and I've encountered a problem that I can't seem to solve. I have two nested for loops that iterate through elements of a two-dimensional array. I need to find the first element that satisfies a certain condition, and once found, immediately stop the execution of both loops. The problem is that a regular break only exits the inner loop, while the outer loop continues to run.
Here's a simplified example of my code:
```java
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 5;
boolean found = false;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
found = true;
break; // exits only the inner loop
```
No answers yet.
Log in to leave an answer
Blogs