Java Reference
In-Depth Information
Chapter 3
Loops
3.1
The
while
Statement
...................................................................
41
3.2
The
do-while
Construct
................................................................
43
...........................................................................
3.3
The
for
Loop
45
.......................................................................
3.4
Nested
for
Loops
49
3.5
The Modulus Operation
................................................................
52
3.6
Summary
................................................................................
54
3.7
Syntax
..................................................................................
54
3.8
Important Points
.......................................................................
55
3.9
Exercises
................................................................................
56
3.10 Lab
......................................................................................
57
3.11 Project
..................................................................................
58
In the previous chapter, we showed how to use the
if
and
switch
statements in order to
choose from several possible program execution paths. In this chapter, we present different
types of flow control structures that are called
loop
structures. These structures allow the
same code segment to be executed multiple times. There are three loop structures in Java:
while
,
do
,and
for
.The
while
structure allows us to repeatedly execute the same block of
code until a condition is met. The
do
structure is similar, but it guarantees that the code
will be executed at least once. The
for
structure is best suited when we know how many
times we want to execute a particular code segment. The chapter also covers the modulus
operator.
3.1 The
while
Statement
First, we will improve on the multiplication game from the last chapter. If the user
entered the wrong number, then we will give the user the option to enter the correct result.
The program should continue asking the user for an answer until the correct answer is
entered. The code from last chapter is shown below.
1
import
java . util .
∗
;
2
public class
Arithmetic
{
3
public static void
main(String [] args)
{
4
int
x=(
int
)
(Math . random ( )
10) ;
∗
5
int
y=(
int
)
(Math . random ( )
10) ;
∗
6
Scanner keyboard =
new
Scanner(System. in) ;
7
System . out . p r i n t ( x +
"*"
+y+
"="
);
8
int
z = keyboard . nextInt () ;
9
if
(z == x
∗
y)
{
10
System . out . p r i n t l n (
"Congratulations!"
);
11
}
else
{
12
System . out . p r i n t l n (
"You need more practice"
);
13
}
41