【发布时间】:2020-07-23 10:02:42
【问题描述】:
在这段代码中,Math.random() 方法应该输出 1、2、3 或 4,并根据输出的数字,在相对位置画一个圆(RandomWalk java 程序的一部分)。
程序不显示随机点的位置,而是只打印向上的点(所以只有当(方向 == 1)用于北)被使用时,如果 Math.random() 方法有问题,我会感到困惑就是这样做的。
代码如下:
int start_x = 200;
int start_y = 200;
double direction;
for (int i = 0; i < 20; i++)
{
// Generates random integer between 1 and 4
direction = (int) Math.random() * 4 + 1;
// North
if (direction == 1)
{
g2.setColor(Color.BLUE);
Ellipse2D.Double circle1
= new Ellipse2D.Double(start_x - 2, start_y - 12, 4, 4);
g2.draw(circle1);
start_y -= 10;
}
// South
if (direction == 2)
{
g2.setColor(Color.BLUE);
Ellipse2D.Double circle1
= new Ellipse2D.Double(start_x - 2, start_y + 8, 4, 4);
g2.draw(circle1);
start_y += 10;
}
// East
if (direction == 3)
{
g2.setColor(Color.BLUE);
Ellipse2D.Double circle1
= new Ellipse2D.Double(start_x + 8, start_y - 2, 4, 4);
g2.draw(circle1);
start_x += 10;
}
if (direction == 4)
{
g2.setColor(Color.BLUE);
Ellipse2D.Double circle1
= new Ellipse2D.Double(start_x - 12, start_y - 2, 4, 4);
g2.draw(circle1);
start_x -= 10;
}
}
【问题讨论】:
-
'Math.random()' cast to 'int' is always rounded down to '0'。请看stackoverflow.com/a/32234865/9740537
标签: java for-loop random graphics