Home » Java » java – How can I use randomisation to specify different object parameters to a single iteration in a loop?-Exceptionshub

java – How can I use randomisation to specify different object parameters to a single iteration in a loop?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I currently have a simple for-loop with 5 iterations that creates ‘brick’ game objects, adds them into the ‘bricks’ array and laying them out across the x axis of my javaFX scene. currently, as you can see on the Gameobj parameters; they are all blue. However, I want to have one of these bricks set as yellow on a random iteration of the loop. Here is my code:

    public void initialiseGame()
    {       
        bricks = new ArrayList<>();
        for(int i=0; i<5; i++) {
            GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
            brick.moveX(75);
            brick.visible = true;
            bricks.add(brick);
            System.out.println("Model:: Create Brick =" + brick);
        }
    }

Here is the game object method setup:

    public GameObj( int x, int y, int w, int h, Color c )
    {
        topX   = x;       
        topY = y;
        width  = w; 
        height = h; 
        colour = c;
    }

How exactly can I use some sort of randomiser to change the colour of the brick on a single iteration?

How to&Answers:

Pick a random number in the range [0, 5) before the loop, and then set the color to yellow if the loop index matches that number:

Random random = new Random();
int yellowBrick = random.nextInt(5);
for (int i = 0; i < 5; i++) {
    Color color = i == yellowBrick ? Color.YELLOW : Color.BLUE;
    GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, color);
    brick.moveX(75);
    brick.visible = true;
    bricks.add(brick);
    System.out.println("Model:: Create Brick =" + brick);
}

Answer:

You can call GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);.

For example:
You can call int random = ThreadLocalRandom.current().nextInt(0, 5) outside the for-loop. And then use this inside the for-loop:

if (random != i) {
  GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
} else {
  GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.YELLOW);
}

For more information on Color visit Java™ Platform
Standard Ed. 8 Documentation

Or you can use the Math.random() function.