【问题标题】:Math.random() function is not working in a for-loop [duplicate]Math.random()函数在for循环中不起作用[重复]
【发布时间】: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;
    }
}

【问题讨论】:

标签: java for-loop random graphics


【解决方案1】:

这可能是因为您将自己的价值投向了早期。 请尝试以下操作:

direction = (int) (Math.random() * 4) + 1; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 2014-11-03
    • 2015-01-05
    • 1970-01-01
    相关资源
    最近更新 更多