Tagged break and Continue (Java)

Source: Internet
Author: User

December 2002 in Ccw-i,
Moved to CSDN in September 2006, slightly modified

There is a goto keyword in Java, but this keyword has no effect, in other words, we cannot use Goto to jump to a row. In fact, structured programming completely does not require a goto statement to complete a variety of processes, and the use of the goto statement tends to make the program less readable, so Java does not allow Goto jump.

You can also define a label in Java, using the multibyte colon (:) form, such as "MyLabel:". However, since the Goto in Java does not have a substantive effect, the design of the label is certainly not for Goto.

The tags in Java are designed for loops and are designed for easy use of break and coutinue in multiple loops. It is for this reason that the Java label can only be defined at the beginning of the three loops (for () {}, do{}, and (), while () {}), otherwise the compiler will report that the label cannot be found. A later example can be described more intuitively.

Adding a label to the loop is like giving the loop a name. When you use a break or continue statement in a loop, you can take this tag as a parameter, indicating which loop jumps out (break) or continues (continue), such as "Break MyLabel;", "Continue mylabel;". Now take a look at example 1 below, to intuitively understand the use of tags, where the comments have roughly explained what each division of code is doing, and the explanation behind the example will make you more aware of:

  Example 1:labelexmaple.java

/*
* @ (#) Labelexample.java
* @author James Fancy
*/

/**
* The Labelexample class will randomly generate a two-dimensional array,
* The data in each row of the array is arranged from small to in order, but the rows are not sorted.
* At the same time, Labelexample will randomly find a number in the resulting two-dimensional array as the data to be found.
* The tag break and continue statements are then used in the search method to refine the lookup code.
*/
public class Labelexample{

/**
* Main program.
*/
public static void Main (string[] args){
Labelexample test = new Labelexample (3, 5);
Test.printmatrix ();
System.out.println ();
Test.search ();
}

int row; Number of rows in a two-dimensional array

int col; Number of data per row for a two-dimensional array

int[][] data; Array data

int lookfor; The number to look up in the array

/**
* constructor to generate an array of columns specified by row, specified by Col.
*/
public labelexample (int row, int col){
This.row = row;
This.col = col;
Creatematrix ();
}

/**
* Print array contents.
*/
public void Printmatrix (){
System.out.println ("row =" + row + ", col =" + col + ", lookfor ="
+ lookfor);
for (int i = 0; i < row; i++){
for (int j = 0; J < Col; J + +){
System.out.print ("" + data[i][j]);
}
System.out.println ();
}
}

/**
* Demonstrates the lookup process, using tagged break and continue statements.
*/
public void Search (){
LOOP1:
If the label is defined here, it will not be omitted because it is not followed by a loop statement.
The ignored tags, if used in break or continue statements, cannot be passed at compile time.
If it is not used in break or continue, the compilation can succeed.
SYSTEM.OUT.PRINTLN ("---Begin searching---");
loop1:for (int i = 0; i < row; i++){
for (int j = 0; J < Col; J + +){
if (Data[i][j] > LookFor){
SYSTEM.OUT.PRINTLN ("---jump---");
Continue LOOP1; Think of the break here and what will happen.
}
if (data[i][j] = = lookfor){
System.out.println ("found:data[" + i + "[" + j + "] ="
+ lookfor);
Break Loop1; Think of the return here and what's going to change.
}
System.out
. println ("data[" + i + "[" + j + "] =" + data[i][j]);
}
SYSTEM.OUT.PRINTLN ("---loop2end---");
}
SYSTEM.OUT.PRINTLN ("---End searching---");
}

/**
* Generate random arrays and randomly extract the number to find.
*/
private void Creatematrix (){
data = new int[row][];
for (int i = 0; i < row; i++){
Data[i] = new Int[col];
int t = 0;
for (int j = 0; J < Col; J + +){
                 t +=  (int)   (math.random ()  * 20);
                data[i][j]  = t;
            }
        }
        lookfor = data[(int)   (math.random ()  *  row) [(int)   (math.random ()  * col)];
    }

}

The results of this program run as follows:

row = 3, col = 5, lookfor = 48
11 21 22) 38 39
14 22 40) 55 72
11 29 38) 48 63

---Begin searching---
Data[0][0] = 11
DATA[0][1] = 21
DATA[0][2] = 22
DATA[0][3] = 38
Data[0][4] = 39
---loop2end---
Data[1][0] = 14
DATA[1][1] = 22
DATA[1][2] = 40
---jump---
Data[2][0] = 11
DATA[2][1] = 29
DATA[2][2] = 38
FOUND:DATA[2][3] = 48
---End searching---

Since all the data in the program is generated randomly, the more representative results are obtained by running the program several times.

In the above program, both the Creatematrix method and the Printmatrix method are tools, one for initializing the data and the other for printing the array. Another method of search is the key to demonstrating the program.

The data that is printed in the search method is sufficient to describe the lookup process. The first for loop (that is, the one labeled LOOP1) is used to traverse all the groups in the two-dimensional array (that is, each row); The second for loop is nested in the first for loop and is used to iterate through all the data in each group so that it can be found sequentially.

If the second for loop does not find the data you are looking for in the process of finding a group of data, there are two cases: 1) The data for this group is all smaller than the data you are looking for, then the loop can be executed completely, then the statement after the loop, the output "---loop2end---". 2) This group of data has data that is larger than the data to be looked up, then continue LOOP1 is executed when the first data that is larger than the data to be searched is checked. This statement not only jumps out of the second for loop, but also aborts the statement that has not yet been executed in the first for loop, making the next loop of the first for loop directly. Here's a question, what if we change continue loop1 to break? If you change it, the input results are:

......
---jump---
---loop2end---
......
The reason for this is that Braek only aborts the second loop, but does not abort the statement that has not yet been executed in the first loop.

Now let's look at what happens when we find the target data. If the target data is found, no matter which loop is executed, it is meaningless. So, to abort two loops. Since the data is found in the second loop, and the second loop is nested in the first loop, the second loop can only be aborted if it is a direct break, and the first loop continues, while the break LOOP1 specifies that the first loop is aborted, since the first loop is aborted. Then the second loop, which relies on the first loop, is, of course, aborted. Here's a question too, why not return it? I think this is a better question than the previous one, because if you use return, what about the statements after these two for loops?

It is important to note that the LOOP1 tag is used for both continue and break. If the code is "SYSTEM.OUT.PRINTLN ("---Begin searching---"); And the "LOOP1:" The position of the two statement exchange, then the results will be what? The compiler will now report that the LOOP1 tag could not be found. This is why the label definition must be followed by the loop statement. However, if there is no break or continue statement in the program to use LOOP1, it does not matter where the LOOP1 definition, the compiler will ignore it.

Finally, add a sentence, generally do not use the label. If you encounter some complex multiple loops, I would prefer to suggest using multiple methods to perform each layer of loops, which would make the program structure clearer.

Tagged break and Continue (Java)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.