Break and for-loops

Just a quick question. I am new to using “break” and I am making a program that checks an integer grid if the number 1 is in an entry. Obviously I don’t want to check the rest of the grid if I have found an entry that is equal to 1. Therefore, I wanted to use “break” but should I use break twice in the inner for-loop to exit the double for-loop?
My overall program is a little more complicated than that but you should get the idea by looking at the code below:

for(int i=0; i< minnumberrow; i++){ // does something for each line in the file
          for(int j=0; j< minnumbercol; j++){ // do something for each collum of each line
            if(int(lines[i].charAt(j))==49){ // if it is a 0 or a 1 (49 seems to be 1 in char)

Yes, break will only break out of the inner-most loop.

A cleaner alternative might be to test against taken in your loop conditions (also, you don’t need to convert your charAt() to an int, just compare it to '1'):

taken = false;
for(int i=0; i< minnumberrow && !taken; i++){ // does something for each line in the file
          for(int j=0; j< minnumbercol && !taken; j++){ // do something for each column of each line
            if(lines[i].charAt(j) == '1') { // if it is a 0 or a 1


You can define a label: right before the outer loop and issue a break using that label name:

boolean taken = false;

for (int i = 0; i < 10; ++i)  for (int j = 0; j < 20; ++j)
  if (i == 5 && j == 15) {
    println(j, i);
    taken = true;
    break taken;

1 Like

When you are in a function of its own, return() command is your friend