for循环中的随机变量

时间:2012-11-09 03:39:22

标签: java random for-loop double scope

我正在尝试在Graphics2D实例上绘制5个方块。对于左上角x坐标和左上角y坐标,5个正方形中的每一个都应具有随机双精度值。

double pixelSize = 2.0;

g2d.setColor(color);

for (int i = 0; i < 5; i++) {
    double nextDouble = gen.nextDouble();
    System.out.println("nextDouble: "+nextDouble);
    double topLeftX = nextDouble*(maxX-minX) + minX;
    System.out.println("topLeftX: "+topLeftX);
    double topLeftY = nextDouble*(maxY-minY) + minY;
    System.out.println("topLeftY: "+topLeftY);

    Shape square = new Rectangle2D.Double(topLeftX, topLeftY, pixelSize, pixelSize);
    g2d.fill(square);
    repaint();
    revalidate();
} 

相反,我从println语句中看到的是,nextDouble值在循环的每次迭代中都在变化,但topLeftXtopLeftY保持不变,即使它们部分来自nextDouble

我希望topLeftXtopLeftY每次都能在循环中更改。

1 个答案:

答案 0 :(得分:1)

它们正在改变,但只是在小数点后的数字中,正如人们所期望的那样,以及maxX-minX和maxY-minY中的单位差异:

nextDouble: 0.731057369148862
topLeftX: 394.73105736914886
topLeftY: 188.73105736914886
nextDouble: 0.07099203475193139
topLeftX: 394.07099203475195
topLeftY: 188.07099203475192

...