Java Reference
In-Depth Information
5.1
Introduction
5.2
Essentials of Counter-Controlled
Repetition
5.3
for
Repetition Statement
5.4
Examples Using the
for
Statement
5.5
do
…
while
Repetition Statement
5.6
switch
Multiple-Selection Statement
5.7
Class
AutoPolicy
Case Study:
String
s in
switch
Statements
5.8
break
and
continue
Statements
5.9
Logical Operators
5.10
Structured Programming Summary
5.11
(Optional) GUI and Graphics Case
Study: Drawing Rectangles and Ovals
5.12
Wrap-Up
Summary | Self-Review Exercises | Answers to Self-Review Exercises | Exercises | Making a Difference
This chapter continues our presentation of structured programming theory and principles
by introducing all but one of Java's remaining control statements. We demonstrate Java's
for
,
do
…
while
and
switch
statements. Through a series of short examples using
while
and
for
, we explore the essentials of counter-controlled repetition. We use a
switch
state-
ment to count the number of A, B, C, D and F grade equivalents in a set of numeric grades
entered by the user. We introduce the
break
and
continue
program-control statements.
We discuss Java's logical operators, which enable you to use more complex conditional ex-
pressions in control statements. Finally, we summarize Java's control statements and the
proven problem-solving techniques presented in this chapter and Chapter 4.
This section uses the
while
repetition statement introduced in Chapter 4 to formalize the
elements required to perform counter-controlled repetition, which requires
1.
a
control variable
(or loop counter)
2.
the
initial value
of the control variable
3.
the
increment
by which the control variable is modified each time through the
loop (also known as
each iteration of the loop
)
4.
the
loop-continuation condition
that determines if looping should continue.
To see these elements of counter-controlled repetition, consider the application of
Fig. 5.1, which uses a loop to display the numbers from 1 through 10.
1
// Fig. 5.1: WhileCounter.java
2
// Counter-controlled repetition with the while repetition statement.
3
4
public class
WhileCounter
5
{
6
public static void
main(String[] args)
7
{
Fig. 5.1
|
Counter-controlled repetition with the
while
repetition statement. (Part 1 of 2.)