A Guide to Java Loops – Java循环指南

最后修改: 2017年 12月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll look at a core aspect of the Java language – executing a statement or a group of statements repeatedly – using loops.

在这篇文章中,我们将看看Java语言的一个核心方面–重复执行一条或一组语句–使用循环。

2. Intro to Loops

2.循环的介绍

In programming languages, looping is a feature which facilitates the execution of a set of instructions until the controlling Boolean-expression evaluates to false.

在编程语言中,looping是一种促进执行一组指令的功能,直到控制Boolean-expression评估为false

Java provides different types of loops to fit any programming need. Each loop has its own purpose and a suitable use case to serve.

Java提供了不同类型的循环,以满足任何编程需要。每个循环都有自己的目的和合适的用例来服务。

Here are the types of loops that we can find in Java:

以下是我们在Java中可以找到的循环的类型。

  • Simple for loop
  • Enhanced for-each loop
  • While loop
  • Do-While loop

3. For Loop

3.For循环

A for loop is a control structure that allows us to repeat certain operations by incrementing and evaluating a loop counter.

for 循环是一种控制结构,它允许我们通过增加和评估一个循环计数器来重复某些操作。

For a detailed example, have a look at the dedicated post: Java For Loop.

关于详细的例子,请看专门的帖子。Java For Loop

4. While Loop

4.While循环

The while loop is Java’s most fundamental loop statement. It repeats a statement or a block of statements while its controlling Boolean-expression is true.

while循环是Java最基本的循环语句。它重复一个语句或一个语句块,同时其控制布尔表达式为真。

For a detailed example, have a look at the dedicated post: Java While Loop.

关于详细的例子,请看专门的帖子。Java While Loop

5. Do-While Loop

5.Do-While 循环

The do-while loop works just like the while loop except for the fact that the first condition evaluation happens after the first iteration of the loop.

除了第一个条件的评估发生在循环的第一次迭代之后,do-while循环的工作方式与while循环相同。

For a detailed example, have a look at the dedicated post: Java Do-While Loop.

关于详细的例子,请看专门的帖子。Java Do-While Loop

6. Conclusion

6.结论

In this quick tutorial, we showed the different types of loops that are available in the Java programming language.

在这个快速教程中,我们展示了Java编程语言中的不同类型的循环。

We also saw how each loop serves a particular purpose given a suitable use case. We discussed the circumstances that are suitable for a given loop implementation.

我们还看到,在一个合适的使用情况下,每个循环是如何服务于一个特定的目的。我们讨论了适合于某个特定循环实现的情况。

As always, examples can be found over on GitHub.

一如既往,可以在GitHub上找到实例