官术网_书友最值得收藏!

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:

  1. Using the techniques from the previous exercise, create a new class named Exercise11.
  2. 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);

        }

    }

  3. 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:

  1. Using the techniques from the previous exercise, create a new class named Exercise12.
  2. Enter a main() method:

    public static void main(String[] args) {

    }

  3. 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.

  4. 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.

  5. 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:

  1. Using the techniques from the previous exercise, create a new class named Exercise13.
  2. Enter a main() method:

    public static void main(String[] args) {

    }

  3. Define a slightly longer array of String values:

    String[] letters = { "A", "B", "C", "D" };

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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:

  1. Using the techniques from the previous exercise, create a new class named Exercise14.
  2. Enter a main() method:

    public static void main(String[] args) {

    }

  3. 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.

  4. 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.

主站蜘蛛池模板: 什邡市| 辽宁省| 临沭县| 特克斯县| 县级市| 济阳县| 甘肃省| 阿尔山市| 上杭县| 图木舒克市| 扎囊县| 镇江市| 桂东县| 昌吉市| 宜阳县| 正安县| 岐山县| 宁河县| 蚌埠市| 盐池县| 芒康县| 西畴县| 西畴县| 利川市| 沅江市| 遂川县| 七台河市| 鄂伦春自治旗| 定远县| 通河县| 镇沅| 昌都县| 思茅市| 洪湖市| 韶山市| 祁东县| 顺义区| 呈贡县| 巴彦县| 石阡县| 黔东|