Skip to content
This repository has been archived by the owner on Apr 9, 2024. It is now read-only.

Commit

Permalink
Merge pull request #28437 from lkxed/20230114-0-A-4-minute-guide-to-J…
Browse files Browse the repository at this point in the history
…ava-loops

[手动选题][tech]: 20230114.0 ⭐️ A 4-minute guide to Java loops.md
  • Loading branch information
wxy authored Jan 15, 2023
2 parents 3483044 + 7fa4095 commit c841422
Showing 1 changed file with 151 additions and 0 deletions.
151 changes: 151 additions & 0 deletions sources/tech/20230114.0 ⭐️ A 4-minute guide to Java loops.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
[#]: subject: "A 4-minute guide to Java loops"
[#]: via: "https://opensource.com/article/23/1/java-loops"
[#]: author: "Seth Kenlon https://opensource.com/users/seth"
[#]: collector: "lkxed"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "

A 4-minute guide to Java loops
======

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.

--------------------------------------------------------------------------------

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

作者:[Seth Kenlon][a]
选题:[lkxed][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

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

[a]: https://opensource.com/users/seth
[b]: https://github.com/lkxed


0 comments on commit c841422

Please sign in to comment.