The while and do-while loops

Một phần của tài liệu Manning OCA java SE 8 programmer i certification guide (Trang 389 - 393)

You’ll learn about while and do-while loops in this section. Both of these loops exe- cute a set of statements as long as their condition evaluates to true. Both of these loops work in the same manner except for one difference: the while loops checks its condition before evaluating its loop body, and the do-while loop checks its condition after executing the statements defined in its loop body.

Does this difference in behavior make a difference in their execution? Yes, it does, and in this section, you’ll see how.

5.5.1 The while loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution of the statement.

For example, at the famous fast-food chain Superfast Burgers, an employee may be instructed to prepare burgers as long as buns are available. In this example, the avail- ability of buns is the while condition and the preparation of burgers is the while’s loop body. You can represent this in code as follows:

boolean bunsAvailable = true;

while (bunsAvailable) {

/* ... prepare burger ...*/

if (noMoreBuns)

bunsAvailable = false;

}

[5.1] Create and use while loops

[5.3] Create and use do-while loops

359 The while and do-while loops

The preceding example is for demonstration purposes only, because the loop body isn’t completely defined. The condition used in the while loop to check whether or not to execute the loop body again should evaluate to false at some point; otherwise, the loop will execute indefinitely. The value of this loop variable may be changed by the while loop or by another method if it’s an instance or a static variable.

The while loop accepts arguments of type boolean or Boolean. In the preceding code, the loop body checks whether more buns are available. If none are available, it sets the value of the variable bunsAvailable to false. The loop body doesn’t execute for the next iteration because bunsAvailable evaluates to false.

The execution of the preceding while loop is shown in figure 5.18 as a simple flow- chart to help you understand the concept better.

Now, let’s examine another simple example that uses the while loop:

int num = 9;

boolean divisibleBy7 = false;

while (!divisibleBy7) { System.out.println(num);

if (num % 7 == 0) divisibleBy7 = true;

--num;

}

Start

No

No

Yes

Yes

bunsAvailable == true?

bunsAvailable = false moreBuns == true?

Prepare burger

Stop while

Statements to execute ifwhile condition evaluates totrue

Figure 5.18 A flowchart depicting the flow of code in a while loop

360 CHAPTER 5 Flow control

The output of this code is as follows:

9 8 7

What happens if you change the code as follows (changes in bold)?

int num = 9;

boolean divisibleBy7 = true;

while (divisibleBy7 == false) { System.out.println(num);

if (num % 7 == 0) divisibleBy7 = true;

--num;

}

The code won’t enter the loop because the condition divisibleBy7==false isn’t true.

5.5.2 The do-while loop

A do-while loop is used to repeatedly execute a set of statements until the condition that it uses evaluates to false. This loop checks the condition after it completes the execution of all the statements in its loop body.

You could compare this structure to a software application that displays a menu at startup. Each menu option will execute a set of steps and redisplay the menu. The last menu option is “exit,” which exits the application and does not redisplay the menu:

boolean exitSelected = false;

do {

String selectedOption = displayMenuToUser();

if (selectedOption.equals("exit")) exitSelected = true;

else

executeCommand(selectedOption);

} while (exitSelected == false);

The preceding code is represented by a simple flowchart in figure 5.19 that will help you to better understand the code.

The preceding example is for demonstration purposes only because the methods used in the do-while loop aren’t defined. As discussed in the previous section on while loops, the condition that’s used in the do-while loop to check whether or not to execute the loop body again should evaluate to false at some point, or the loop will execute indefinitely. The value of this loop variable may be changed by the while loop or by another method, if it’s an instance or static variable.

NOTE Don’t forget to use a semicolon (;) to end the do-while loop after specifying its condition. Even some experienced programmers overlook this step!

361 The while and do-while loops

The do-while loop accepts arguments of type boolean or Boolean.

Let’s modify the example used in section 5.5.1 to use the do-while loop instead of a while loop, as follows:

int num = 9;

boolean divisibleBy7 = false;

do {

System.out.println(num);

if (num % 7 == 0) divisibleBy7 = true;

num--;

} while (divisibleBy7 == false);

The output of this code is as follows:

9 8 7

No

No

Yes

Yes Stop

selectedOption == exit?

Start

Display menu to user

AcceptselectedOption

exitSelected = true

exitSelected == true? while do

executeCommand(selectedOption)

Figure 5.19 Flowchart showing the flow of code in a do-while loop

362 CHAPTER 5 Flow control

What happens if you change the code as follows (changes in bold)?

int num = 9;

boolean divisibleBy7 = true;

do {

System.out.println(num);

if (num % 7 == 0) divisibleBy7 = true;

num--;

} while (divisibleBy7 == false);

The output of the preceding code is as follows:

9

The do-while loop executes once, even though the condition specified in the do-while loop evaluates to false because the condition is evaluated at the end of execution of the loop body.

5.5.3 while and do-while block, expression, and nesting rules

You can use the curly braces {} with while and do-while loops to define multiple lines of code to execute for every iteration. Without the use of curly braces, only the first line of code will be considered a part of the while or do-while loop, as specified in the if-else construct in section 5.1.3.

Similarly, the rules that define an appropriate expression to be passed to while and do-while loops are the same as for the if-else construct in section 5.1.4. Also, the rules for defining nested while and do-while loops are the same as for the if-else construct in section 5.1.5.

Một phần của tài liệu Manning OCA java SE 8 programmer i certification guide (Trang 389 - 393)

Tải bản đầy đủ (PDF)

(706 trang)