Java Reference
In-Depth Information
for
(
int
i=0; i
<
n ; i ++)
{
System. out . print (c) ;
}
}
Now we can rewrite our code for printing a diamond as follows.
import
java . util .
∗
;
public class
Diamond
{
public static void
printStrings(String s ,
int
n)
{
for
(
int
i=0; i
<
n ; i ++)
{
System. out . print ( s ) ;
}
}
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)
{
printStrings(
""
,numSpaces) ;
printStrings(
"* "
,numStars) ;
System. out . println () ;
for
(
int
numStars=size
−
2, numSpaces = 2; numStars
>
=0 ; numSpaces
+=2, numStars
−
=2 )
{
printStrings(
""
,numSpaces) ;
printStrings(
"* "
,numStars) ;
System. out . println () ;
}
}
}
The code is not necessarily shorter, but it is easier to understand. When we want to
print a number of characters, we simply call our friend
printStrings
. He will print as many
stringsaswewantforfree!Next,notethatweprintalineinthesamewaywhenweprint
the top and the bottom of the diamond. Therefore, we can create a method that prints a
line.
public static void
printLine(
int
numSpaces ,
int
numStars)
{
printStrings(
""
,numSpaces) ;
printStrings(
"* "
,numStars) ;
System. out . println () ;
}
Now, our main method will call the
printLine
method when we want to print a line. The
number of spaces and stars in the line are specified as parameters. The
printLine
method
in turn calls the
printStrings
method twice to print the spaces and stars, respectively.
The new version of the code is shown below.
import
java . util .
∗
;
public class
Diamond
{
public static void
printStrings(String s ,
int
n)
{
for
(
int
i=0;i
<
n ;
i ++)
{
System. out . print ( s ) ;