Java Reference
In-Depth Information
23
for
(
int
line = 0; line
<
s i z e / 2 ;
l i n e ++)
{
24
for
(
int
i=0;i
<
numSpaces ;
i++)
{
25
System . out . p r i n t (
""
);
26
}
27
for
(
int
i=0;i
<
numStars ;
i++)
{
28
System . out . p r i n t (
"* "
);
29
}
30
System . out . p r i n t l n ( ) ;
31
numSpaces += 2;
32
numStars
−
=2;
33
}
}
34
}
35
Lines 8-20 print the top part of the diamond, while Lines 21-33 print the bottom half.
Note that the variable
i
is used as a counter. Traditionally, the counter is referred to as
an
iterator
by programmers and, as a consequence,
i
is a common name for the counter
variable. The first part of the code tells the computer to print
siz
2
+ 1 lines. The variable
line
is used as the counter variable. When printing a line, we print
numSpaces
spaces and
numStars
stars. Next, we update the value of the variables. Note that Line 17 prints a new
line. The
println
method does not require a parameter. If it is called without a parameter,
then just a new line is printed.
An experienced programmer probably will not introduce the variable
line
. The reason is
that either the variable
numSpaces
or the variable
numStars
can be used to decide when to
stop the
for
loop. We will keep executing the first
for
loop while the
numSpaces
is greater
or equal to 0. We will keep executing the second
for
loop while the
numStars
is greater or
equal to 0. Note that the condition inside the
for
statement is exactly the opposite (or the
negation) of the loop terminating condition.
import
java . util .
∗
;
public class
Diamond
{
public static void
main(String [] args)
{
Scanner keyboard =
new
Scanner(System. in) ;
System. out . print (
"Enter size of diamond: "
);
int
size = keyboard.nextInt() ;
for
(
int
numStars =1, numSpaces = size
−
>
1; numSpaces
=0; numSpaces
−
=2, numStars+=2)
{
for
(
int
i=0;i
<
numSpaces ;
i++)
{
System. out . print (
""
);
for
(
int
i=0;i
<
numStars ;
i++)
{
System. out . print (
"* "
);
System. out . println () ;
for
(
int
numStars=size
−
2, numSpaces = 2; numStars
>
0; numSpaces+=2,
numStars
−
=2 )
{
for
(
int
i=0;i
<
numSpaces ;
i++)
{
System. out . print (
""
);
for
(
int
i=0;i
<
numStars ;
i++)
{
System. out . print (
"* "
);
System. out . println () ;