Mas e ai? O que fazer?
Muito simples:
Utilize a instrução "break label"
Estrutura:
//label
sair:{
//laços
break sair;
}
Aqui vai um exemplo:
public class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i = 0;
int j = 0;
boolean foundIt = false;
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i = 0;
int j = 0;
boolean foundIt = false;
//label
search:
for ( ;i < arrayOfInts.length; i++) {
for (j=0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
search:
for ( ;i < arrayOfInts.length; i++) {
for (j=0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
//break label
break search;
}
}
}
if (foundIt)
System.out.println("Found " + searchfor + " at " + i + ", " + j);
else
System.out.println(searchfor + "not in the array");
}
}
break search;
}
}
}
if (foundIt)
System.out.println("Found " + searchfor + " at " + i + ", " + j);
else
System.out.println(searchfor + "not in the array");
}
}
Mesmo que o laço interno não tenha terminado, ele será encerrado e o laço externo também.
Nenhum comentário:
Postar um comentário