金字塔坐标
Coordinates of pyramid
好了,现在清楚一些了。我的问题是整数 i。为什么现在每次迭代第一个 for 循环时都会从 i 中减去 1。
import acm.graphics.;
import acm.util.;
import acm.program.*;
public class 金字塔扩展 GraphicsProgram {
public void run() {
pyramid();
}
private GRect brick() {
GRect brick = new GRect(30,12);
return brick;
}
private void pyramid() {
int xCoord = 0;
int yCoord = getHeight()-BRICK_HEIGHT;
for (int k = 0; k<=12;k++) {
i--;
for (i=12; i>=1;i--) {
add(brick(),xCoord,yCoord);
xCoord += BRICK_WIDTH;
}
yCoord -= BRICK_HEIGHT;
xCoord = 0;
}
}
private int i;
private static final int BRICK_WIDTH = 30;
private static final int BRICK_HEIGHT = 12;
private static final int BRICKS_IN_BASE = 12;
}
保持简单。没有 class 个变量,除了 static final,没有字段。您可以用一种方法完成所有操作;几乎没有充分的理由使用其他方法。
private void pyramid(){
int xBase = 0;
int yCoord = getHeight() - BRICK_HEIGHT;
// 12 rows of decreasing length: 12, 11,... 1
for( int rowlen = 12; rowlen >= 1; --rowlen ){
// lay the bricks - calculate x-coordinate
for( int iBrick = 0; iBrick < rowlen; ++iBrick ){
add( brick(), xBase + iBrick*BRICK_WIDTH, yCoord );
}
// indent for next row
xBase += 15;
// advance vertically
yCoord -= BRICK_HEIGHT;
}
好了,现在清楚一些了。我的问题是整数 i。为什么现在每次迭代第一个 for 循环时都会从 i 中减去 1。
import acm.graphics.; import acm.util.; import acm.program.*;
public class 金字塔扩展 GraphicsProgram {
public void run() {
pyramid();
}
private GRect brick() {
GRect brick = new GRect(30,12);
return brick;
}
private void pyramid() {
int xCoord = 0;
int yCoord = getHeight()-BRICK_HEIGHT;
for (int k = 0; k<=12;k++) {
i--;
for (i=12; i>=1;i--) {
add(brick(),xCoord,yCoord);
xCoord += BRICK_WIDTH;
}
yCoord -= BRICK_HEIGHT;
xCoord = 0;
}
}
private int i;
private static final int BRICK_WIDTH = 30;
private static final int BRICK_HEIGHT = 12;
private static final int BRICKS_IN_BASE = 12;
}
保持简单。没有 class 个变量,除了 static final,没有字段。您可以用一种方法完成所有操作;几乎没有充分的理由使用其他方法。
private void pyramid(){
int xBase = 0;
int yCoord = getHeight() - BRICK_HEIGHT;
// 12 rows of decreasing length: 12, 11,... 1
for( int rowlen = 12; rowlen >= 1; --rowlen ){
// lay the bricks - calculate x-coordinate
for( int iBrick = 0; iBrick < rowlen; ++iBrick ){
add( brick(), xBase + iBrick*BRICK_WIDTH, yCoord );
}
// indent for next row
xBase += 15;
// advance vertically
yCoord -= BRICK_HEIGHT;
}