什么是“继续”? 关键字以及它在 Java 中如何工作?

发布于 2024-07-10 22:33:15 字数 130 浏览 10 评论 0原文

我第一次看到这个关键字,我想知道是否有人可以向我解释它的作用。

  • Continue 关键字是什么?
  • 它是如何工作的?
  • 什么时候使用?

I saw this keyword for the first time and I was wondering if someone could explain to me what it does.

  • What is the continue keyword?
  • How does it work?
  • When is it used?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

掩于岁月 2024-07-17 22:33:16

Continue 是 Java 和 Java 中的关键字。 它用于跳过当前迭代。

假设你想打印从 1 到 100 的所有奇数

public class Main {

    public static void main(String args[]) {

    //Program to print all odd numbers from 1 to 100

        for(int i=1 ; i<=100 ; i++) {
            if(i % 2 == 0) {
                continue;
            }
            System.out.println(i);
        }

    }
}

继续 上面程序中的语句只是在 i 为偶数时跳过迭代并打印 i< /strong> 当它是奇数时。

Continue 语句只是让您退出循环,而不执行循环内的其余语句并触发下一次迭代。

Continue is a keyword in Java & it is used to skip the current iteration.

Suppose you want to print all odd numbers from 1 to 100

public class Main {

    public static void main(String args[]) {

    //Program to print all odd numbers from 1 to 100

        for(int i=1 ; i<=100 ; i++) {
            if(i % 2 == 0) {
                continue;
            }
            System.out.println(i);
        }

    }
}

continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.

Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.

╭ゆ眷念 2024-07-17 22:33:16

考虑 If Else 条件。 continue 语句执行条件中的内容并跳出条件,即跳转到下一个迭代或条件。 但是 Break 会离开循环。
考虑以下程序。 '

public class ContinueBreak {
    public static void main(String[] args) {
        String[] table={"aa","bb","cc","dd"};
        for(String ss:table){
            if("bb".equals(ss)){
                continue;
            }
            System.out.println(ss);
            if("cc".equals(ss)){
                break;
            }
        }
        System.out.println("Out of the loop.");
    }

}

它将打印:aa cc 跳出循环。

如果你使用break代替continue(After if.),它只会打印aa并跳出循环

如果满足条件“bb”等于 ss:
对于继续:进入下一次迭代,即“cc”.equals(ss)。
For Break:它跳出循环并打印“跳出循环”。

Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop.
Consider the following Program. '

public class ContinueBreak {
    public static void main(String[] args) {
        String[] table={"aa","bb","cc","dd"};
        for(String ss:table){
            if("bb".equals(ss)){
                continue;
            }
            System.out.println(ss);
            if("cc".equals(ss)){
                break;
            }
        }
        System.out.println("Out of the loop.");
    }

}

It will print: aa cc Out of the loop.

If you use break in place of continue(After if.), it will just print aa and out of the loop.

If the condition "bb" equals ss is satisfied:
For Continue: It goes to next iteration i.e. "cc".equals(ss).
For Break: It comes out of the loop and prints "Out of the loop. "

半寸时光 2024-07-17 22:33:16

continue 语句用于循环控制结构中,当您需要立即跳转到循环的下一次迭代时。

它可以与 for 循环或 while 循环一起使用。
Java continue 语句用于继续循环。 它继续程序的当前流程并在指定条件下跳过剩余代码。

如果是内部循环,则仅继续内部循环。

我们可以在所有类型的循环中使用 Java continue 语句,例如 for 循环、while 循环和 do-while 循环。

例如

class Example{
    public static void main(String args[]){
        System.out.println("Start");
        for(int i=0; i<10; i++){
            if(i==5){continue;}
            System.out.println("i : "+i);   
        }
        System.out.println("End.");
    }
}

输出:

Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.

[数字 5 是跳过]

The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.

It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.

In case of an inner loop, it continues the inner loop only.

We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.

for example

class Example{
    public static void main(String args[]){
        System.out.println("Start");
        for(int i=0; i<10; i++){
            if(i==5){continue;}
            System.out.println("i : "+i);   
        }
        System.out.println("End.");
    }
}

output:

Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.

[number 5 is skip]

生来就爱笑 2024-07-17 22:33:16

我参加聚会有点晚了,但是...

值得一提的是,continue 对于空循环很有用,其中所有工作都在条件表达式控制中完成循环。 例如:

while ((buffer[i++] = readChar()) >= 0)
    continue;

在本例中,读取字符并将其附加到 buffer 的所有工作都是在控制 while 循环的表达式中完成的。 continue 语句充当循环不需要主体的视觉指示器。

它比等效的更明显一点:

while (...)
{ }

并且绝对比使用空语句更好(更安全)的编码风格:

while (...)
    ;

I'm a bit late to the party, but...

It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:

while ((buffer[i++] = readChar()) >= 0)
    continue;

In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.

It's a little more obvious than the equivalent:

while (...)
{ }

and definitely better (and safer) coding style than using an empty statement like:

while (...)
    ;
白芷 2024-07-17 22:33:16

continue 必须在循环内,否则会显示以下错误:

在循环外继续

continue must be inside a loop Otherwise it showsThe error below:

Continue outside the loop

抱着落日 2024-07-17 22:33:15

继续有点像goto。 您熟悉break吗? 相比之下,考虑它们更容易:

  • break 终止循环(跳转到其下面的代码)。

  • Continue 终止当前迭代循环内代码的其余处理,但继续循环。

continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:

  • break terminates the loop (jumps to the code below it).

  • continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.

莫相离 2024-07-17 22:33:15

继续 没有标签的语句将从最内层 whiledo 循环的条件以及最内层 for< 的更新表达式重新执行/代码> 循环。 它通常用于提前终止循环的处理,从而避免深度嵌套的 if 语句。 在下面的示例中,continue 将获取下一行,而不处理循环中的以下语句。

while (getNext(line)) {
  if (line.isEmpty() || line.isComment())
    continue;
  // More code here
}

使用标签时,continue 将从具有相应标签的循环中重新执行,而不是最内层循环。 这可以用来逃避深层嵌套的循环,或者只是为了清晰起见。

有时,continue 也用作占位符,以使空循环体更加清晰。

for (count = 0; foo.moreData(); count++)
  continue;

C 和 C++ 中也存在相同的不带标签的语句。 Perl 中的等效项是 next

不建议使用这种类型的控制流,但如果您选择,也可以使用 continue 来模拟有限形式的 goto。 在以下示例中,continue 将重新执行空的 for (;;) 循环。

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;

A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.

while (getNext(line)) {
  if (line.isEmpty() || line.isComment())
    continue;
  // More code here
}

With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.

Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.

for (count = 0; foo.moreData(); count++)
  continue;

The same statement without a label also exists in C and C++. The equivalent in Perl is next.

This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;
浅忆 2024-07-17 22:33:15

让我们看一个例子:

int sum = 0;
for(int i = 1; i <= 100 ; i++){
    if(i % 2 == 0)
         continue;
    sum += i;
}

这将得到 1 到 100 之间的奇数之和。

Let's see an example:

int sum = 0;
for(int i = 1; i <= 100 ; i++){
    if(i % 2 == 0)
         continue;
    sum += i;
}

This would get the sum of only odd numbers from 1 to 100.

不必了 2024-07-17 22:33:15

如果您将循环体视为子例程,则 continue 有点像 return。 C 中也存在相同的关键字,并且具有相同的用途。 这是一个人为的示例:

for(int i=0; i < 10; ++i) {
  if (i % 2 == 0) {
    continue;
  }
  System.out.println(i);
}

这将仅打印出奇数。

If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:

for(int i=0; i < 10; ++i) {
  if (i % 2 == 0) {
    continue;
  }
  System.out.println(i);
}

This will print out only the odd numbers.

梦途 2024-07-17 22:33:15

一般来说,我将 continue (和 break)视为代码可能使用一些重构的警告,特别是如果 while 或 for 循环声明不是立即可见的。 对于方法中间的 return 也是如此,但原因略有不同。

正如其他人已经说过的,continue 移动到循环的下一次迭代,而 break 则移出封闭循环。

这些可能是维护定时炸弹,因为除了上下文之外,继续/中断与其正在继续/中断的循环之间没有直接链接; 添加内部循环或将循环的“内容”移至单独的方法中,并且您会产生 continue/break 失败的隐藏效果。

恕我直言,最好将它们用作最后​​的手段,然后确保它们的使用在循环的开始或结束时紧密地组合在一起,以便下一个开发人员可以在一个屏幕中看到循环的“边界” 。

continuebreakreturn(除了方法末尾的 One True Return 之外)都属于“隐藏”的一般类别转到”。 他们将循环和函数控制放在意想不到的地方,最终导致错误。

Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.

These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.

IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.

continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.

榕城若虚 2024-07-17 22:33:15

Java中的“继续”意味着转到当前循环的末尾,
意思是:如果编译器在循环中看到 continue ,它将进入下一次迭代

示例:这是一个打印从 1 到 10 的奇数的代码,

每当编译器看到 continue 进入下一次迭代时,它都会忽略打印代码

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}

"continue" in Java means go to end of the current loop,
means: if the compiler sees continue in a loop it will go to the next iteration

Example: This is a code to print the odd numbers from 1 to 10

the compiler will ignore the print code whenever it sees continue moving into the next iteration

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}

浪漫之都 2024-07-17 22:33:15

正如已经提到的,continue 将跳过处理其下面的代码,直到循环结束。 然后,您将移至循环的条件,如果该条件仍然成立(或者如果有标志,则转到指定循环的条件),然后运行下一次迭代。

必须强调的是,在 do - while 的情况下,您将在 continue 之后移动到底部的条件,而不是在循环的开头。

这就是为什么很多人无法正确回答以下代码将生成什么。

    Random r = new Random();
    Set<Integer> aSet= new HashSet<Integer>();
    int anInt;
    do {
        anInt = r.nextInt(10);
        if (anInt % 2 == 0)
            continue;
        System.out.println(anInt);
    } while (aSet.add(anInt));
    System.out.println(aSet);

*如果您的答案是 aSet 将仅 100% 包含奇数...您就错了!

As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).

It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.

This is why a lot of people fail to correctly answer what the following code will generate.

    Random r = new Random();
    Set<Integer> aSet= new HashSet<Integer>();
    int anInt;
    do {
        anInt = r.nextInt(10);
        if (anInt % 2 == 0)
            continue;
        System.out.println(anInt);
    } while (aSet.add(anInt));
    System.out.println(aSet);

*If your answer is that aSet will contain odd numbers only 100%... you are wrong!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文