Java process control (IV) interrupt

In programming, the direct jump of the loop is very important. Although Java does not provide goto statements to control the jump of the program, in order to control the loop, Java provides continue, break, and special tags to implement specific interrupts and jumps. Of course, return is relatively different. This article will make a summary.

break

For example, the following simple example:

for (int i = 0;i<10 ;i++ ) {
    System.out.println(i);
    if(i==1) break;
}
System.out.println("跳出循环");//输出 0 1 跳出循环

Until, if there is no if (I = = 1) break; In this statement, the loop will output numbers 0-9 in turn, but after adding this sentence, if you execute the break statement when I is equal to 1, you will directly jump out of the loop.

continue

Still give an example:

for (int i = 0;i<10 ;i++ )
{	
    if(i%2==0) continue;
    System.out.println(i);
}
System.out.println("跳出循环");
//输出1 3 5 7 9 跳出循环

return

for (int i = 0;i<10 ;i++ ) {
    System.out.println(i);
    if(i==1) return;
}
System.out.println("跳出循环");//输出 0 1 

label

Break and continue match labels are similar, but there are differences.

The label needs to be placed before the loop statement, otherwise it has no meaning. The specific form is as follows: Label:

outer:
for (int i = 0;i<5 ;i++ ) {
    for (int j = 0;j<3 ;j++ ) {
        System.out.print(" i="+i+" j="+j);
        if(j==1)
        {
            break outer;
        }
        System.out.println();
    }

}
//输出
 i=0 j=0
 i=0 j=1

When J = = 1, a break outer statement is encountered, resulting in the end of the loop specified by the outer tag, not the loop where the break is ended! Not the loop where break ends!!!!

outer:
for (int i = 0;i<5 ;i++ ) {
    for (int j = 0;j<3 ;j++ ) {
        System.out.print(" i="+i+" j="+j);
        if(j==1)
        {
            continue outer;
        }
        System.out.println();
    }
}
//输出
 i=0 j=0
 i=0 j=1 i=1 j=0
 i=1 j=1 i=2 j=0
 i=2 j=1 i=3 j=0
 i=3 j=1 i=4 j=0
 i=4 j=1

The value of J will never exceed 1, because whenever J = 1, the continue outer statement ends the outer label control loop. When this loop directly starts the next loop, I starts from I + 1 and j starts from 0.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>