Does the break statement break out of loops or onl

2019-01-24 06:16发布

In the following code, does the break statement break out of the if statement only or out of the for loop too?

I need it to break out of the loop too.

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

标签: java break
8条回答
Animai°情兽
2楼-- · 2019-01-24 06:29

That would break out of the for loop. In fact break only makes sense when talking about loops, since they break from the loop entirely, while continue only goes to the next iteration.

查看更多
戒情不戒烟
3楼-- · 2019-01-24 06:29

An unlabelled break only breaks out of the enclosing switch, for, while or do-while construct. It does not take if statements into account.

See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html for more details.

查看更多
地球回转人心会变
4楼-- · 2019-01-24 06:30

It breaks the loop, but why not explicitly put the condition in the for itself? It would be more readable and you would not have to write the if statement at all

(if i==temp then temp = i is totally pointless)

查看更多
beautiful°
5楼-- · 2019-01-24 06:31

break is to break out of any loop.

查看更多
Deceive 欺骗
6楼-- · 2019-01-24 06:37

It will break out of the loop always.

查看更多
Rolldiameter
7楼-- · 2019-01-24 06:48

Break never refers to if/else statements. It only refers to loops (if/while) and switch statements.

查看更多
登录 后发表回答