Java Reference
In-Depth Information
method printStars , which has two parameters: a parameter to specify the number of
blanks before the stars in a line and another parameter to specify the number of stars in a
line. The definition of the method printStars is:
public static void printStars( int blanks, int starsInLine)
{
int count = 1;
//print the number of blanks before the stars in a line
for (count <= blanks; count++)
System.out.print("");
//print the number of stars with a blank between stars
for (count = 1; count <= starsInLine; count++)
System.out.print(" *");
System.out.println();
} //end printStars
The first parameter, blanks , determines how many blanks to print preceding the star(s);
the second parameter, starsInLine , determines how many stars to print in a line. If the
value of the parameter blanks is 30 , for instance, then the first for loop in the method
printStars executes 30 times and prints 30 blanks. Also, because you want to print
spaces between the stars, every iteration of the second for loop in the method
printStars prints the string " *" (Line 30)—a blank followed by a star.
Next consider the following statements:
int numberOfLines = 15;
int numberOfBlanks = 30;
int counter = 1;
7
for (counter = 1; counter <= numberOfLines; counter++)
{
printStars(numberOfBlanks, counter);
numberOfBlanks--;
}
The for loop calls the method printStars . Every iteration of this for loop specifies the
number of blanks followed by the number of stars to print in a line, using the variables
numberOfBlanks and counter . Every invocation of the method printStars receives
one fewer blank and one more star than the previous call. For example, the first iteration of
the for loop in the method main specifies 30 blanks and 1 star (which are passed as the
parameters, numberOfBlanks and counter , to the method printStars ). The for
loop then decrements the number of blanks by 1 by executing the statement,
numberOfBlanks--; . At the end of the for loop, the number of stars is incremented
by 1 for the next iteration. This is done by executing the update statement, counter++ ,in
the for statement, which increments the value of the variable counter by 1 . In other
words, the second call of the method printStars receives 29 blanks and 2 stars as
parameters. Thus, the previous statements will print a triangle of stars consisting of 15 lines.
Search WWH ::




Custom Search