在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ 在Java中,使用goto語句跳出嵌套循環(huán)是一種好的編程實(shí)踐嗎

在Java中,使用goto語句跳出嵌套循環(huán)是一種好的編程實(shí)踐嗎

Branching Statements

在java中可以使用帶標(biāo)簽的break語句來跳出嵌套的循環(huán)。

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = { 
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:  // 定義標(biāo)簽
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;  //帶標(biāo)簽的break語句
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

在我的印象中,學(xué)習(xí)軟件工程時(shí),書上說要避免使用goto語句。在java中,帶標(biāo)簽的break就是goto的一種實(shí)現(xiàn)。那么遇到需要跳出嵌套循環(huán)的情況,這樣處理好嗎?
或者有其他更好的方法?

回答
編輯回答
氕氘氚

對于很深層的循環(huán)來說,使用break跳出更容易理解。但是能不用的就不要用。所以書上才說“避免使用”而不是“禁止使用”。像例子里的兩層的就沒必要用這個,可以抽象出來一個searchInMatrix的方法來做

2018年1月4日 12:58