简体   繁体   English

Java for循环,我需要继续声明吗?

[英]Java for-loop, do i need continue statement here?

Consider this code: 考虑以下代码:

if (int a == 0) {
    System.out.println("hello");
    continue;
}

This if is part of a for loop in java. 这个if是java中for循环的一部分。 What is the significane of continue statement here? 这里继续声明的意义何在? I know continue is the opposite of break so that it wont break out of the loop rather just skip that iteration for anything below it. 我知道continuebreak的反面,所以它不会突破循环而只是跳过那个迭代以下的任何东西。 But in case it is inside an if statement, do I really need it like this? 但是如果它在if语句中,我真的需要这样吗?

No, you don't need to use continue there, you can use an else block instead: 不,你不需要在那里continue使用,你可以使用else块代替:

    if (a == 0) {
         System.out.println("hello");
    } else {
         // The rest of the loop body goes here.
    }

Which is better is a style issue. 哪个更好是一个风格问题。 Sometimes one is better, sometimes the other - it depends on what the typical flow should be and which flow you want to emphasize in the code. 有时一个更好,有时一个更好 - 这取决于典型流程应该是什么以及您希望在代码中强调哪些流程。

If this is the last statement of the for loop - no, you don't need it. 如果这是for循环的最后一个语句 - 不,你不需要它。 Otherwise you need it to skip everything below the if -clause. 否则你需要它跳过if -clause下面的所有内容。 If you don't want to skip it, then don't use continue . 如果您不想跳过它,请不要使用continue

Here is an explanation with examples of what continue is doing. 以下是对 continue做什么的示例的解释

continue means that the statements below the if block won't work. continue表示if块下面的语句不起作用。 If this is the behavior you need, you should continue . 如果这是您需要的行为,您应该continue Otherwise it is not needed. 否则就不需要了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM