- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 1584字
- 2021-06-11 13:05:20
Looping and Performing Repetitive Tasks
In this chapter, we cover using loops to perform repetitive tasks. The main types of loop are as follows:
- for loops
- while loops
- do-while loops
for loops repeat a block a set number of times. Use a for loop when you are sure how many iterations you want. A newer form of the for loop iterates over each item in a collection.
while loops execute a block while a given condition is true. When the condition becomes false, the while loop stops. Similarly, do-while loops execute a block and then check a condition. If true, the do-while loop runs the next iteration.
Use while loops if you are unsure how many iterations are required. For example, when searching through data to find a particular element, you normally want to stop when you find it.
Use a do-while loop if you always want to execute the block and only then check if another iteration is needed.
Looping with the for Loop
A for loop executes the same block of code for a given number of times. The syntax comes from the C language:
for(set up; boolean expression; how to increment) {
// Execute these statements…
}
In the preceding code, we can see that:
- Each part is separated by a semicolon, (;).
- The set up part gets executed at the beginning of the entire for loop. It runs once.
- The boolean expression is examined at each iteration, including the first. So long as this resolves to true, the loop will execute another iteration.
- The how to increment part defines how you want a loop variable to increment. Typically, you'll add one for each increment.
The following exercise will implement a classic for loop in Java.
Exercise 11: Using a Classic for Loop
This exercise will run a for loop for four iterations, using the classic for loop syntax:
- Using the techniques from the previous exercise, create a new class named Exercise11.
- Enter a main() method and the following code:
public static void main(String[] args) {
for (int i = 1; i < 5; i++) {
System.out.println("Iteration: " + i);
}
}
- Run the Exercise11 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Here is how the program executes:
- int i = 1 is the for loop set up part.
- The Boolean expression checked each iteration is i < 5.
- The how to increment part tells the for loop to add one to each iteration using the ++ operator.
- For each iteration, the code inside the parentheses executes. It continues like this until the Boolean expression stops being true.
In addition to the old classic for loop, Java also offers an enhanced for loop designed to iterate over collections and arrays.
We will cover arrays and collections in greater detail later in the book; for now, think of arrays as groups of values of the same data type stored in a single variable, whereas collections are groups of values of different data types stored in a single variable.
Exercise 12: Using an Enhanced for Loop
Iterating over the elements of arrays means that the increment value is always 1 and the start value is always 0. This allows Java to reduce the syntax of a form to iterate over arrays. In this exercise you will loop over all items in a letters array:
- Using the techniques from the previous exercise, create a new class named Exercise12.
- Enter a main() method:
public static void main(String[] args) {
}
- Enter the following array:
String[] letters = { "A", "B", "C" };
Chapter 4, Collections, Lists, and Java's Built-In APIs, will cover the array syntax in greater depth. For now, we have an array of three String values, A, B, and C.
- Enter an enhanced for loop:
for (String letter : letters) {
System.out.println(letter);
}
Notice the reduced syntax of the for loop. Here, the variable letter iterates over every element in the letters array.
- Run the Exercise12 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
A
B
C
Jumping Out of Loops with Break and Continue
A break statement, as we saw in the switch examples, jumps entirely out of a loop. No more iterations will occur.
A continue statement jumps out of the current iteration of the loop. Java will then evaluate the loop expression for the next iteration.
Exercise 13: Using break and continue
This exercise shows how to jump out of a loop using break, or jump to the next iteration using continue:
- Using the techniques from the previous exercise, create a new class named Exercise13.
- Enter a main() method:
public static void main(String[] args) {
}
- Define a slightly longer array of String values:
String[] letters = { "A", "B", "C", "D" };
- Enter the following for loop:
for (String letter : letters) {
}
This loop will normally iterate four times, once for each letter in the letters array. We'll change that though, with the next code.
- Add a conditional to the loop:
if (letter.equals("A")) {
continue; // Jump to next iteration
}
Using continue here means that if the current letter equals A, then jump to the next iteration. None of the remaining loop code will get executed.
- Next, we'll print out the current letter:
System.out.println(letter);
For all iterations that get here, you'll see the current letter printed.
- Finish the for loop with a conditional using break:
if (letter.equals("C")) {
break; // Leave the for loop
}
If the value of letter is C, then the code will jump entirely out of the loop. And since our array of letters has another value, D, we'll never see that value at all. The loop is done when the value of letter is C.
- Run the Exercise13 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
B
C
Exercise13.java holds the full example:
Note
Source code for Exercise 13 can be found at the following link: https://packt.live/2MDczAV.
Using the while Loop
In many cases, you won't know in advance how many iterations you need. In that case, use a while loop instead of a for loop.
A while loop repeats so long as (or while) a Boolean expression resolves to true:
while (boolean expression) {
// Execute these statements…
}
Similar to a for loop, you'll often use a variable to count iterations. You don't have to do that, though. You can use any Boolean expression to control a while loop.
Exercise 14: Using a while Loop
This exercise implements a similar loop to Exercise10, which shows a for loop:
- Using the techniques from the previous exercise, create a new class named Exercise14.
- Enter a main() method:
public static void main(String[] args) {
}
- Enter the following variable setting and while loop:
int i = 1;
while (i < 10) {
System.out.println("Odd: " + i);
i += 2;
}
Note how this loop increments the i variable by two each time. This results in printing odd numbers.
- Run the Exercise14 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9
Note
A common mistake is to forget to increment the variable used in your Boolean expression.
Using the do-while Loop
The do-while loop provides a variant on the while loop. Instead of checking the condition first, the do-while loop checks the condition after each iteration. This means with a do-while loop, you will always have at least one iteration. Normally, you will only use a do-while loop if you are sure you want the iteration block to execute the first time, even if the condition is false.
One example use case for the do-while loop is if you are asking the user a set of questions and then reading the user's response. You always want to ask the first question.
The basic format is as follows:
do {
// Execute these statements…
} while (boolean expression);
Note the semicolon after the Boolean expression.
A do-while loop runs the iteration block once, and then checks the Boolean expression to see if the loop should run another iteration.
Example17.java shows a do-while loop:
public class Example17 {
public static void main(String[] args) {
int i = 2;
do {
System.out.println("Even: " + i);
i += 2;
} while (i < 10);
}
}
This example prints out even numbers.
Note
You can use break and continue with while and do-while loops too.
- Learning Neo4j
- Vue.js設計與實現
- Learning Selenium Testing Tools with Python
- 深入淺出Prometheus:原理、應用、源碼與拓展詳解
- Groovy for Domain:specific Languages(Second Edition)
- Windows Presentation Foundation Development Cookbook
- JavaScript入門經典
- 學習正則表達式
- 深入理解Elasticsearch(原書第3版)
- Python之光:Python編程入門與實戰
- 蘋果的產品設計之道:創建優秀產品、服務和用戶體驗的七個原則
- AMP:Building Accelerated Mobile Pages
- Penetration Testing with the Bash shell
- JavaEE架構與程序設計
- INSTANT LESS CSS Preprocessor How-to