http://big5.china.com/gate/big5/kaoshi.china.com/java/learning/639351-1.htm


  Java語言中goto是保留關鍵字,沒有goto語句,也沒有任何使用goto關鍵字的地方。

  Java中也可在特定情況下,通過特定的手段,來實現goto的功能。顯然Java不願意開發者隨意跳轉程式。下面解釋兩個特定:

  特定情況:只有在迴圈體內,比如for、while語句(含do.……while語句)中。

  特定手段:語句標簽和迴圈控制關鍵字break、continue,語法格式是:break/continue 語句標簽。

  break、continue和語句標簽

  1、語句標簽

  語句標簽的語法是:標簽名:

  語句標簽可以定義在方法體內的最後一條語句之前即可。但是語句標簽實際使用的機會是與break和continue結合使用的,而break和continue是和迴圈語句結合使用的,因此實際上語句標簽的使用也是和迴圈緊密結合的。

  語句標簽在被使用的情況,只能定義在迴圈迭代語句之前,否則編譯出錯!

  因此,有意義、可使用的標簽含義是:指定迴圈語句的標識!

  2、break、continue語句單獨使用

  單獨使用情況下:break語句作用是結束當前的迴圈迭代體,進而執行剩餘的語句。

  continue語句的作用是結束本次迭代過程,繼續執行下一輪迭代。

  3、break、continue語句結合語句標簽的使用

  為什麼需要語句標簽呢?

  原因是因為程式可能有迴圈的嵌套,當多層迴圈嵌套時候,有時候需要一次跳出多級迴圈,這種情況下就需要結合語句標簽才能實現此功能了。

  帶標簽使用情況下:break中斷並跳出標簽所指定迴圈,continue跳轉到標簽指定的迴圈處,並繼續執行該標簽所指定的迴圈。

  為了說明情況,看看下面的例子:

public class TestLable {

    public static void main(String〔〕 args) {

    outer:
        for (int i = 0; i 《 10; i++) {
            System.out.println(“\nouter_loop:” + i);
            inner:
            for (int k = 0; i 《 10; k++) {
                System.out.print(k + “ ”);
                int x = new Random()。nextInt(10);
                if (x 》 7) {
                    System.out.print(“ 》》x == ” + x + “,結束inner迴圈,繼續迭代執行outer迴圈了!”);
                    continue outer;
                }
                if (x == 1) {
                    System.out.print(“ 》》x == 1,跳出並結束整個outer和inner迴圈!”);
                    break outer;
                }
            }
        }
        System.out.println(“——》》》所有迴圈執行完畢!”);
    }
}

  執行結果:
  outer_loop:0

  0 1 2 3 4 5 6 7 8 9 》》x == 8,結束inner迴圈,繼續迭代執行outer迴圈了!

  outer_loop:1

  0 1 2 3 4 5 》》x == 9,結束inner迴圈,繼續迭代執行outer迴圈了!

  outer_loop:2

  0 1 2 3 4 5 6 7 8 9 》》x == 8,結束inner迴圈,繼續迭代執行outer迴圈了!

  outer_loop:3

  0 1 2 3 4 》》x == 9,結束inner迴圈,繼續迭代執行outer迴圈了!

  outer_loop:4

  0 1 2 3 4 5 6 7 8 9 10 》》x == 8,結束inner迴圈,繼續迭代執行outer迴圈了!

  outer_loop:5

  0 》》x == 1,跳出並結束整個outer和inner迴圈!——》》》所有迴圈執行完畢!

  Process finished with exit code 0

 

===業界實際案例===

    mainProcess: 
        for (int i = 0; i < 100; i++) {
            try {
                if (i > 0) {
                    logger.info("重作次數:" + i);
                }
                map = XManager.doMainProcess(inputMap);
                break;
            } catch (Exception e) {
                String errorMsg = e.getMessage();
                String msg = "gov.fck.common.exception.FCKExceptionAdvice]"
                    + "[FCK017-傳遞的引數不符合所呼叫參數規格][An error occurred while processing registered class";
                if (errorMsg.indexOf(msg) != -1) {
                    continue mainProcess;
                } else {
                    logger.error(e.getMessage());
                }
            }
        }

文章標籤
全站熱搜
創作者介紹
創作者 DED 的頭像
DED

DED的部落格

DED 發表在 痞客邦 留言(0) 人氣(1)