Java使用break語句?

2019-10-16 22:30:22

在Java中,如何使用使用break語句?

下面範例中,演示如何使用break語句跳出迴圈(實現查詢數值:1122,找到後退出迴圈)

package com.yiibai;

public class UseOfBreakStatement {
    public static void main(String[] args) {
        int[] intary = { 199, 212, 252, 34, 5, 1122, 67, 5678, 8990 };
        int no = 1122;
        int i = 0;
        boolean found = false;

        for (; i < intary.length; i++) {
            if (intary[i] == no) {
                found = true;
                break;
            }
        }
        if (found) {
            System.out.println("Found the no: " + no + " at  index: " + i);
        } else {
            System.out.println(no + "not found  in the array");
        }
    }
}

執行上面範例程式碼,得到以下結果 -

Found the no: 1122 at  index: 5