Java Math.random()函数在for循环中不起作用
在这段代码中,Math.random方法应该输出1、2、3或4,并根据输出的数字,在RandomWalk java程序的相对位置部分绘制一个圆 该程序没有显示随机点位置,而是只打印向上的点,因此只使用了ifdirection==1表示North,我不知道Math.random方法是否有问题,正是这个方法让它这样做的 代码如下:Java Math.random()函数在for循环中不起作用,java,for-loop,random,graphics,Java,For Loop,Random,Graphics,在这段代码中,Math.random方法应该输出1、2、3或4,并根据输出的数字,在RandomWalk java程序的相对位置部分绘制一个圆 该程序没有显示随机点位置,而是只打印向上的点,因此只使用了ifdirection==1表示North,我不知道Math.random方法是否有问题,正是这个方法让它这样做的 代码如下: int start_x = 200; int start_y = 200; double direction; for (int i = 0; i &
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;
}
}
这可能是因为你很早就把你的价值投给了别人。 请尝试以下操作:
direction = (int) (Math.random() * 4) + 1;
这可能是因为你很早就把你的价值投给了别人。 请尝试以下操作:
direction = (int) (Math.random() * 4) + 1;
转换为“int”的“Math.random”始终向下舍入为“0”。请参阅转换为“int”的“Math.random”总是向下舍入为“0”。请看