The break statement
*FIGURE 1. The structure of a break statement
break ümumilikdə dövrlərdə (loop) və switch ifadələrində işlədilir. Onu təkcə if`in içində işlətdikdə compile error verir, if`in içində işlətsək və həmin if özü də dövrün içində olsa onda normal compile olacaq.
for(;;)
if(true){
System.out.println("Infinite loop break");
break;
}
Nümunəyə baxaq:
public static void main(String[] args) {
int[][] array = { {1,13,5}, {1,2,5}, {2,7,2} };
int searchValue = 2;
int px = -1;
int py = -1;
PARENT_LOOP: for(int x=0; x<array.length; x++){
for(int y=0; y<array[x].length; y++){
if(array[x][y] == searchValue){
px = x;
py = y;
/*Insert code*/ // line1
}
}
}
if(px==-1 || py==-1)
System.out.println("Value "+searchValue+" not found!");
else
System.out.println("Value "+searchValue+" found at: ("+px+", "+py+")");
}
Əgər line1`ə aşağıdakı ifadələr əlavə olunarsa nəticə belə dəyişəcək:
break PARENT_LOOP;⇒ Value 2 found at: (1,1);break;⇒ Value 2 found at: (2,0);- remove break ⇒ Value 2 found at: (2,2);
Aşağıdakı nümunəyə Coderanch forumunda rast gəldim, deməli if ifadəsi əgər dövrün (loop) içində deyilsə, break label; işləyəcək, amma tək break; işləməyəcək:
void test1(){
int value = 2;
label:
if (value > 1) {
if (value <= 2) {
break label; // əgər “label” yazılmasa tək break; compile olunmayacaq
}
System.out.println("More than two");
}
System.out.println("Done");
}
void test2(){
int value = 2;
if (value > 1) {
if (value <= 2) {
break; // DOES NOT COMPILE
}
System.out.println("More than two");
}
System.out.println("Done");
}
Yadda saxlamaq lazımdır ki, break label; və ya continue label; ifadələri mütləq label elan olunan dövrün (loop) daxilində olmalıdır. Label`in xaricindən həmin label`a müraciət etmək mümkün deyil. Enthuware test bankında belə bir sual nümunəsi qarşınıza çıxacaq:
public void testBreak(int i) {
int j = (i * 30 - 2) / 100;
POINT1: for (; j < 10; j++) {
boolean flag = false;
while (!flag) {
if (Math.random() > 0.5) break POINT1;
}
}
while (j > 0) {
System.out.println(j--);
if (j == 4) break POINT1; // does NOT compile
}
}
The continue statement
**FIGURE 2. The structure of a continue statement
Nümunə:
FIRST_LOOP: for (int i = 1; i <= 4; i++) {
for (char j = 'a'; j <= 'c'; j++) {
if (i == 2 || j == 'b') {
/*Insert code*/ // line1
}
System.out.print(" " + i + j);
}
}
Əgər line1`ə aşağıdakı ifadələr əlavə olunarsa nəticə belə dəyişəcək:
continue FIRST_LOOP;⇒ 1a 3a 4acontinue;⇒ 1a 1c 3a 3c 4a 4c- remove continue ⇒ 1a 1b 1c 2a 2b 2c 3a 3b 3c 4a 4b 4c
***TABLE 1. Advanced flow control usage
*Labels are allowed for any block statement, including those that are preceded with an if-then statement.
[topics lang=az]


