Java Reference
In-Depth Information
The following program draws the white pyramid in the correct position:
1 import java.awt.*;
2
3 // Draws the first pyramid only, with a lot of redundancy.
4 public class Pyramids1 {
5
public static void main(String[] args) {
6
DrawingPanel panel = new DrawingPanel(350, 250);
7
Graphics g = panel.getGraphics();
8
9
// draws the border rectangle
10
g.drawRect(0, 0, 100, 100);
11
12
// draws the 10 "stairs" in the white pyramid
13
g.drawRect(45, 0, 10, 10);
14
g.drawRect(40, 10, 20, 10);
15
g.drawRect(35, 20, 30, 10);
16
g.drawRect(30, 30, 40, 10);
17
g.drawRect(25, 40, 50, 10);
18
g.drawRect(20, 50, 60, 10);
19
g.drawRect(15, 60, 70, 10);
20
g.drawRect(10, 70, 80, 10);
21
g.drawRect( 5, 80, 90, 10);
22
g.drawRect( 0, 90, 100, 10);
23
}
24 }
Looking at the code, it's clear that there's a lot of redundancy among the 10 lines
to draw the stairs. Examining the patterns of numbers in each column reveals that the
x value decreases by 5 each time, the y value increases by 10 each time, the width
increases by 10 each time, and the height stays the same.
Another way of describing a stair's x value is to say that it is half of the overall
100 minus the stair's width. With that in mind, the following for loop draws the 10
stairs without the previous redundancy:
for (int i = 0; i < 10; i++) {
int stairWidth = 10 * (i + 1);
int stairHeight = 10;
int stairX = (100 - stairWidth) / 2;
int stairY = 10 * i;
g.drawRect(stairX, stairY, stairWidth, stairHeight);
}
Search WWH ::




Custom Search