嵌套for循环以创建金字塔

时间:2013-11-21 13:56:07

标签: java swing loops nested

我想知道是否有人可以帮助解决这个问题。我一直试图使用嵌套for循环显示金字塔,我只能使第一行(基行)工作。金字塔假设底部有10个矩形,当它增加时,矩形数减少到9,8,7,6等。我一直在看这几天并没有运气。

谢谢!

public class Legos2 extends JFrame {
private int startX;
private int startY;
private int legoWidth;
private int legoHeight;
private int baseLength;
private int arcWidth;
private int arcHeight;

// Constructor
public Legos2() {
    super("Jimmy's LEGOs");
    startX = 20;
    startY = 300;
    legoWidth = 50;
    legoHeight = 20;
    baseLength = 10;
    arcWidth = 2;
    arcHeight = 2;
}

// The drawings in the graphics context
public void paint(Graphics g) 
{

    // Call the paint method of the JFrame
    super.paint(g);


    int currentX = startX;
    int currentY = startY;

    //row = 0 is the bottom row
    for (int row = 1; row <= baseLength; row++)
    {   
        currentX = currentX + legoWidth;
        if (row % 2 == 0)
            g.setColor(Color.blue);
        else
            g.setColor(Color.red);
        System.out.println(row);


        for (int col = 0; col <= baseLength; col++)
        {
            System.out.println(col);
            g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);

        }
        //currentY = currentY - legoHeight;
    }
}

// The main method
public static void main(String[] args) {
    Legos2 app = new Legos2();
    // Set the size and the visibility
    app.setSize(700, 500);
    app.setVisible(true);
    // Exit on close is clicked
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

1 个答案:

答案 0 :(得分:2)

currentY值应该在外循环的每次迭代中递减:对于每一行,你想从较低的Y重新启动。所以你应该取消注释该行

//currentY = currentY - legoHeight;

currentX必须在每列之后递增,因此在内部循环的末尾,而不是在外部循环的开头。在进入内循环之前,必须将其重置为当前行的起始X位置。

如果您只是将currentX重置为startX,那么您将获得一堵砖墙。但是你需要一个金字塔。所以在外循环的每次迭代中应该少一次内循环的迭代,并且在外循环的每次迭代之后startX也应该递增:

    for (int row = 1; row <= baseLength; row++) {
        currentX = startX;
        if (row % 2 == 0) {
            g.setColor(Color.blue);
        }
        else {
            g.setColor(Color.red);
        }
        System.out.println("row = " + row);


        for (int col = 0; col <= baseLength - row; col++) {
            System.out.println("col = " + col);
            g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);
            currentX = currentX + legoWidth;
        }
        currentY -= legoHeight;
        startX += legoWidth / 2;
    }