在Java中,使用goto语句跳出嵌套循环是一种好的编程实践吗

Branching Statements

在java中可以使用带标签的break语句来跳出嵌套的循环。

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:  // 定义标签
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;  //带标签的break语句
                }
            }
        }

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

在我的印象中,学习软件工程时,书上说要避免使用goto语句。在java中,带标签的break就是goto的一种实现。那么遇到需要跳出嵌套循环的情况,这样处理好吗?
或者有其他更好的方法?

阅读 3.6k
1 个回答

对于很深层的循环来说,使用break跳出更容易理解。但是能不用的就不要用。所以书上才说“避免使用”而不是“禁止使用”。像例子里的两层的就没必要用这个,可以抽象出来一个searchInMatrix的方法来做

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进