Java語法介紹(七):Brake和Label

字號:

1:break
     break語句提供了一種方便的跳出循環(huán)的方法。
    boolean test=true;
    int i=0;
    while(test)
    {
       i++;
      if(i>=10) break;
    }
    執(zhí)行這段程序時,盡管while條件表達式始終為真,全循環(huán)只運行10次。
    2:標號label
    標號提供了一種簡單的break語句所不能實現的控制循環(huán)的方法,當在循環(huán)語句中遇到break時,不管其它控制變量,都會終止。但是,當你嵌套在幾層循環(huán)中想退出循環(huán)時又會怎樣呢?正常的break只退出一重循環(huán),你可以用標號標出你想退出哪一個語句。
    char a;
    outer: //this is the label for the outer loop
    for(int i=0;i<10;i++)
    {
    for(int j=0;j<10;j++)
     {
     a=(char)System.in.read();
     if(a==´b´)
       break outer;
     if(a==´c´)
       continue outer;
     }
    }
    在這個例子中,循環(huán)從鍵盤接受100個輸入字符,輸入“b”字符時,break outer語句會結束兩重循環(huán),注意continue outer語句,它告訴計算機退出現在的循環(huán)并繼續(xù)執(zhí)行outer循環(huán)。