Java 循环语句的简要指南
while 循环
![](/data/attachment/album/202301/31/093057lesc38vufbuzustm.jpg)



> 
> 无论你使用的是 `while` 循环、`do`/`while` 循环，还是无限循环，了解循环的工作原理对 Java 编程至关重要。
> 
> 
> 


只要某些预定的条件为真，一个 `while` 循环就会执行一组任务。这被认为是一个控制结构，可以指导程序的流程。它是一种你可以通过定义一个条件来告诉你的代码要做什么的方法，它可以测试它，并根据它发现的情况采取行动。Java 中的两种 `while` 循环是 `while` 和 `do`/`while`。


### Java while 循环


`while` 循环的目的是对数据进行迭代，直到某个条件得到满足。要创建一个 `while` 循环，你需要提供一个可以测试的条件，然后是你想要运行的代码。Java 有几个内置的测试函数，其中最简单的是数学运算符（`<`, `>`, `==`, 等等）：



```
package com.opensource.example;

public class Example {
  public static void main(String[] args) {

  int count = 0;
  while (count < 5) {
    System.out.printf("%d ", count);
    count++;
    }
  }
}

```

在这个简单的例子中，条件是变量 `count` 小于 5。因为 `count` 被实例化为 0，然后在 `while` 循环的代码中增加 1，所以程序总共迭代了 5 次：



```
$ java ./while.java
0 1 2 3 4

```

在它进行第六次迭代之前，条件不再是真的，所以循环结束。


`while` 循环的条件语句是至关重要的。弄错了可能意味着你的循环永远不会执行。例如，假设你把 `count == 5` 作为条件：



```
while (count == 5) {
    System.out.printf("%d ", count);
    count++;

```

当你运行这段代码时，它的构建和运行都很成功，但什么也没有发生：



```
$ java ./while.java
$

```

循环被跳过了，因为 `count` 被设置为 0，而且在第一次遇到 while 循环的时候，它还是 0。循环从未开始，`count` 也从未被递增。


与此相反的是，当一个条件开始为真，并且永远不会为假时，这将导致一个无限循环。


### Java do while 循环


与 `while` 循环相似，`do`/`while` 循环在每次迭代结束时测试条件，而不是在开始时测试条件。有了这个循环，循环中的代码至少运行一次，因为没有进入的入口，只有退出的出口:



```
package com.opensource.example;

public class Example {
  public static void main(String[] args) {

  int count = 9;
  do {
      System.out.printf("%d ", count);
      count++;
    } while(count == 5);
  }
}

```

在这个示例代码中，`count` 被设置为 9。循环重复的条件是 `count` 等于 5，但是 9 不等于 5。不过，这个检查要到第一次迭代结束时才进行：



```
$ java ./do.java
9

```

### Java 无限循环


无限循环，正如它的名字所示，永远不会结束。有时它们是被错误地创建的，但无限循环确实有一个有效的场景。有时你想让一个进程无限地继续下去（在功能上是无限的，因为你不能保证你需要它什么时候停止），因此你可能会把你的条件设置为不可能满足的东西。


假设你写了一个应用程序，在僵尸天启期间计算留在你附近的僵尸的数量。为了模拟需要多少个循环才能达到 0 个僵尸的不确定性，我的演示代码从操作系统中检索了一个时间戳，并将计数器（`c`）的值设置为从该时间戳得出的某个数字。因为这是一个简单的例子，你不会真的想陷入一个无限循环，这段代码倒数到 0，并使用 `break` 函数来强制结束循环：



```
package com.opensource.example;

public class Example {
  public static void main(String[] args) {

  long myTime = System.currentTimeMillis();

  int c;

  if ( myTime%2 == 0 ) {
      c = 128;
  } else {
      c = 1024;
  }

  while(true) {
    System.out.printf("%d Zombies\n", c);

    // break for convenience
    if ( c <= 0 ) { break; }
    c--;
    }
  }
}

```

你可能要运行几次才能触发不同的僵尸总数，但有时你的程序会迭代 128 次，有时会迭代 1024 次：



```
$ java ./zcount.java
1024 Zombies
1023 Zombies
[...]
0 Zombies

```

你能说出为什么循环的终点是 0 而不是 -1 吗？


### Java 循环


循环使你能够控制程序的执行流程。迭代在编程中很常见，无论你使用 `while` 循环、`do`/`while` 循环还是无限循环，了解循环的工作原理都是至关重要的。




---


via: <https://opensource.com/article/23/1/java-loops>


作者：[Seth Kenlon](https://opensource.com/users/seth) 选题：[lkxed](https://github.com/lkxed) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
A while loop performs a set of tasks for as long as some predefined condition is true. This is considered a control structure that directs the flow of a program. It's a way for you to tell your code what to do by defining a condition that it can test, and take action based on what it finds. The two kinds of while loops in Java are while and do while.

## Java while loop

A while loop is meant to iterate over data until some condition is satisfied. To create a while loop, you provide a condition that can be tested, followed by the code you want to run. Java has several built-in test functions, the simplest of which are mathematical operators (`<`

, `>`

, `==`

, and so on):

```
``````
package com.opensource.example;
public class Example {
public static void main(String[] args) {
int count = 0;
while (count < 5) {
System.out.printf("%d ", count);
count++;
}
}
}
```


In this simple example, the condition is that the variable `count`

is less than 5. Because `count`

is instantiated at 0, and then incremented by 1 in the code within the while loop, the program iterates a total of 5 times:

```
``````
$ java ./while.java
0 1 2 3 4
```


Before it can iterate a sixth time, the condition is no longer true, so the loop ends.

The conditional statement for a while loop is vital. Getting it wrong could mean that your loop never executes. For instance, suppose you had set `count == 5`

as the condition:

```
``````
while (count == 5) {
System.out.printf("%d ", count);
count++;
```


When you run the code, it builds and runs successfully, but nothing happens:

```
``````
$ java ./while.java
$
```


The loop has been skipped because `count`

was set to 0, and it's still 0 at the moment the while loop is first encountered. The loop never has a reason to start and `count`

is never incremented.

The reverse of this is when a condition starts as true and can never be false, this results in an infinite loop.

## Java do while loop

Similar to the while loop, a do while loop tests for the conditional at the end, not the beginning, of each iteration. With this, the code in your loop runs at least once because there's no gateway to entry, only a gateway to exit:

```
``````
package com.opensource.example;
public class Example {
public static void main(String[] args) {
int count = 9;
do {
System.out.printf("%d ", count);
count++;
} while(count == 5);
}
}
```


In this sample code, `count`

is set to 9. The condition for the loop to repeat is that `count`

is equal to 5. But 9 isn't equal to 5. That check isn't performed until the end of the first iteration, though:

```
``````
$ java ./do.java
9
```



## Java infinite loops

An infinite loop, as its name suggests, never ends. Sometimes they're created by mistake, but an infinite loop does have a valid use case. Sometimes you want a process to continue indefinitely (that's functionally infinite because you can't guarantee when you need it to stop), and so you might set your condition to something impossible to meet.

Suppose you've written an application that counts the number of zombies remaining in your neighborhood during a zombie apocalypse. To simulate uncertainty over how many loops are required to get to 0 zombies, my demo code retrieves a timestamp from the operating system and sets the value of the counter (`c`

) to some number derived from that timestamp. Because this is a simple example and you don't really want to get trapped in an infinite loop, this code counts down to zero and uses the `break`

function to force the loop to end:

```
``````
package com.opensource.example;
public class Example {
public static void main(String[] args) {
long myTime = System.currentTimeMillis();
int c;
if ( myTime%2 == 0 ) {
c = 128;
} else {
c = 1024;
}
while(true) {
System.out.printf("%d Zombies\n", c);
// break for convenience
if ( c <= 0 ) { break; }
c--;
}
}
}
```


You may have to run it a few times to trigger a different total number of zombies, but sometimes your program iterates 128 times and other times 1,024 times:

```
``````
$ java ./zcount.java
1024 Zombies
1023 Zombies
[...]
0 Zombies
```


Can you tell why the loops end at 0 and not at -1?

## Java loops

Loops give you control over the flow of your program's execution. Iteration is common in programming, and whether you use a while loop, a do while loop, or an infinite loop, understanding how loops work is vital.

## Comments are closed.