Java Reference
In-Depth Information
These definitions create constants called
HEIGHT
and
WIDTH
that will always have
the values
10
and
20
. These are known as class constants, because we declare them
in the outermost scope of the class, along with the methods of the class. That way,
they are visible in each method of the class.
We've already mentioned that we can avoid using a magic number in the
DrawCone
program by introducing a constant for the number of lines. Here's what the constant
definition looks like:
public static final int LINES = 5;
We can now replace the
5
in the outer loop with this constant and replace the
11
in the second inner loop with the expression
2 * LINES + 1
. The result is the fol-
lowing program:
1
public class
DrawCone2 {
2
public static final int
LINES = 5;
3
4
public static void
main(String[] args) {
5
for
(
int
line = LINES; line >= 1; line--) {
6
for
(
int
i = 1; i <= (line - 1); i++) {
7 System.out.print(" ");
8 }
9
int
stars = 2 * LINES + 1 - 2 * line;
10
for
(
int
i = 1; i <= stars; i++) {
11 System.out.print("*");
12 }
13 System.out.println();
14 }
15 }
16 }
Notice that in this program the expression for the number of stars has become suf-
ficiently complex that we've introduced a local variable called
stars
to store the
value. The advantage of this program is that it is more readable and more adaptable.
A simple change to the constant
LINES
will make it produce a figure with a different
number of lines.
Now we'll consider an example that is even more complex. To solve it, we will follow
three basic steps:
1.
Decompose the task into subtasks, each of which will become a static method.
2.
For each subtask, make a table for the figure and compute formulas for each
column of the table in terms of the line number.
3.
Convert the tables into actual
for
loop code for each method.
Search WWH ::
Custom Search