【问题标题】:is there another way to exit a loop without a break statement [duplicate]是否有另一种方法可以在没有break语句的情况下退出循环[重复]
【发布时间】:2016-02-08 07:02:57
【问题描述】:

我只是好奇,因为我经常使用 break 语句,但显然有人告诉我这是不好的做法。显然,从逻辑上讲,如果遇到某些事情,它也可能终止。我就是想知道除了break还有没有别的。

【问题讨论】:

标签: java


【解决方案1】:

关于break的使用,you could check here.

由于没有涵盖 while 循环(我个人经常使用的另一种循环形式),您可以查看循环的设置条件,例如

boolean flag = true;
while (flag) {
    //do something that modifies the below condition
    if (condition) {
        //do something
        flag = false;
    }
}

当条件等于真时循环将终止,因为这会将标志设置为假。

【讨论】:

    【解决方案2】:

    这将打破 for 循环。事实上 break 只在谈论循环时才有意义,因为它们完全从循环中中断,而 continue 只进入下一次迭代 试试这个:

    for(int i= 0; i<MAX; i++){
    if(listEmpt[i] == null){
        listEmpt[i] = employeeObj;
        i=MAX;
    }
    

    但我认为使用中断没有问题。总会有你想停止处理循环并使用中断的情况;比将循环计数器设置为使循环在下一次迭代停止的值更有意义(并使其更具可读性!)。

    您还可以使用可以打破外部循环(和任意代码块)的标记中断

    looplbl: for(int i=;i<;i++){
    
    if (i == temp)
        // do something
    else {
        temp = i;
        break looplbl;
    }
    

    }

    未标记的中断仅从封闭的 switch、for、while 或 do-while 结构中中断。它不考虑 if 语句。

    See for more details.

    【讨论】:

      【解决方案3】:

      如果您只是从循环中返回,那就足够了。大多数人认为您必须终止循环,但事实并非如此。

      另外,请参阅answer

      【讨论】:

        猜你喜欢
        • 2014-05-14
        • 2013-09-16
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 2018-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多