什么是“继续"?关键字以及它在 Java 中是如何工作的? [英] What is the "continue" keyword and how does it work in Java?

查看:25
本文介绍了什么是“继续"?关键字以及它在 Java 中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

A continue 没有标签的语句将从最里面的条件重新执行whiledo 循环,并且来自最里面的 for 循环的更新表达式.它通常用于提前终止循环的处理,从而避免深度嵌套的 if 语句.在下面的例子中,continue 将得到下一行,不处理循环中的以下语句.

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
}

带有标签,continue 将从带有相应标签的循环中重新执行,而不是从最里面的循环开始.这可以用来逃避深层嵌套的循环,或者只是为了清楚起见.

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.

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

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;

同样的没有标签的语句在C和C++中也存在.Perl 中的等效项是 next.

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

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

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;

这篇关于什么是“继续"?关键字以及它在 Java 中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆