There are two commands that can be used to modify the normal execution path of loops: break
and continue
The break
causes the loop is completed immediately, continuing execution from the instruction after the key that closes the code of the loop.
The code between the break
and the key is ignored.
This example code looks for the number 12 no array. The break
ends the loop when the value is found.
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts =
{ 32, 87, 3, 589,
12, 1076, 2000,
8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
The continue
causes the execution to jump to the line where the key that closes the code of the loop, by having his condition assessed, loop will perform again if she is true
.
The code between the continue
and the key is ignored.
The code of the following example goes through string counting all occurrences of the letter p. If the parsed letter is not a p continue causes the next code to be ignored and is passed to the next letter.
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
if (searchMe.charAt(i) != 'p')
continue; // se não é 'p' buscar próxima letra
// Mais um 'p' encontrado
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
If I understand your question correctly, break
. Your code would look like this:
for(int i=0; i<mat.length; i++){
for(int j=0; j<matrizFemininaArryn.length; j++){
if(mat[i][5].equals("Feminino") && mat[i][4].equals("Arryn")){
matrizFemininaArryn[j] = mat[i][0];
break;
}
}
}//após a execução do break a execução salta para aqui terminado o ciclo 'j'
//continuando o ciclo 'i'
Both the break
like the continue
act in relation to the loop where they are inserted.
If you want them to refer to loops outside, they are associated with a label indicating to which loop refer.
Suppose you wanted your code to end both loops when the condition of if
were true.
The code would be like this:
//Identifica-se o loop com um 'label'
search:
for(int i=0; i<mat.length; i++){
for(int j=0; j<matrizFemininaArryn.length; j++){
if(mat[i][5].equals("Feminino") && mat[i][4].equals("Arryn")){
matrizFemininaArryn[j] = mat[i][0];
break search; //Adicionado o 'label' seach
}
}
}
//após a execução do break a execução salta para aqui terminado o ciclo 'j'e o ciclo 'i'
Source of the sample code: Java documentation