2015-10-01 44 views
-1

好吧,現在它更清晰一點。我的問題是整數我。現在它是如何實現的,每次迭代第一個for循環時,現在就從中減去1。金字塔的座標

import acm.graphics。 ; import acm.util。; import acm.program。*;

公共類金字塔擴展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; 

}

+2

你能澄清一下嗎? _「爲什麼我的第一行的行號是兩行?」_ – CubeJockey

+0

爲什麼是'Y_COORDINATE'和''**靜態**字段?他們爲什麼是田野呢?爲什麼'Y_COORDINATE'全部大寫,通常表示一個常量? for循環之後'i - ;'的目的是什麼?代碼中沒有'x座標',所以你在說什麼? – Andreas

+0

@trobins當你運行該程序時,第二行(從底部開始計數)幾乎開始於等於第一行結束的x座標處。 – Alex5207

回答

1

保持簡單。沒有類變量,除了靜態決賽,沒有字段。你可以用一種方法做到這一切;使用其他方法幾乎沒有很好的理由。

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; 
    }