如何根据数组中的项目填充矩形?

时间:2015-05-09 18:38:13

标签: java arrays graphics generator

所以基本上,我需要生成一个1和0的数组,然后填充一定数量的矩形。矩形是“正方形”,需要形成一个更大的正方形。说,我希望我的大方块宽500像素,并且填充100个正方形,所以我需要10个长度为10的阵列 - 我部分成功 - 然后我需要填充小方块取决于如果数组1-1为1,则应填充生成的数组的索引,如square 1-1,依此类推。

public void run() {
    int tableSize = readInt("Enter the size of the table in pixels: ");
    int squareNumber = readInt("Enter the number of squares in a row: ");
    filler(arrayGen(squareNumber), tableSize, squareNumber);
    }

private double[] arrayGen(int A) {
    double[] arr1 = new double[A];
    for (int i = 0; i < arr1.length; i++) {
        arr1[i] = (Math.random() < 0.5 ? 0 : 1);
    }
    return arr1;
}

private void filler(double[] A, int x, int y) {
    for (int i = 0; i < A.length; i++){
        for (int x1 = 0; x1 < x; x1+=(x/y)) {
            GRect rect1 = new GRect (x1, 0, x/y, x/y);
            rect1.setFilled(true);
            rect1.setFillColor(Color.blue);
            if (A[i] == 1) {
                add(rect1);
            }
         }
      }
   }
}

这是我想出的,它仍然缺少一些部分,即如何生成以下行,但如上所述,我的主要问题是数组。

谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码与A [i]和第i个正方形无关。 filler运行外循环A.length次,并且在内循环中创建的矩形都使用相同的A[i]值来确定它们是否应该被填充,因此它们是否全部填充或全部empty取决于A数组中的最后一个值。

看起来你的filler方法只会为大方块的第一行创建矩形。