Chapter 6. Loops and Strings
Computers are often used to automate repetitive tasks, such as searching for text in documents. Repeating tasks without making errors is something that computers do well and people do poorly.
In this chapter, you’ll learn how to use while
and for
loops to add repetition to your code. We’ll also take a first look at String
methods and solve some interesting problems.
The while Statement
Using a while
statement, we can repeat the same code multiple times:
int
n
=
3
;
while
(
n
>
0
)
{
System
.
out
.
println
(
n
);
n
=
n
-
1
;
}
System
.
out
.
println
(
"Blastoff!"
);
Reading the code in English sounds like this: “Start with n
set to 3
. While n
is greater than 0, print the value of n
, and reduce the value of n
by 1. When you get to 0, print Blastoff!
So the output is as follows:
3 2 1 Blastoff!
The flow of execution for a while
statement is shown here:
Evaluate the condition in parentheses, yielding
true
orfalse
.If the condition is
false
, skip the following statements in braces.If the condition is
true
, execute the statements and go back to step 1.
This type of flow is called a loop, because the last step “loops back around” to the first. Figure 6-1 shows this idea using a flowchart.
The body of the loop should change the value of one or more variables so that, eventually, the condition becomes false
and the loop terminates. Otherwise, ...
Get Think Java, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.