jeudi 23 juillet 2020

Java: Random function is not working in a for-loop

In this piece of code, the Math.random() method is supposed to output either 1, 2, 3, or 4 and according to which number was outputted, draw a circle in a relative location (part of RandomWalk java program).

Instead of showing random dot locations, the program only prints dots going up (so only if(direction == 1) for North) was used, and I am confused if there is a problem with the Math.random() method that is making it do this.

Here is the code:

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;
    }
}



Aucun commentaire:

Enregistrer un commentaire