0

So i have made this program and i wanted it t create a 8 by 8 sized image with only Black and White but it does only display a white color instead of randomly spread black and white. Here is my code. If someone can help that'd be great :D

package de.gamingengine.main;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.File;
import javax.imageio.ImageIO;

public class Main {

    public static void main(String args[])throws IOException {

        int width = 8;
        int height = 8;
        Color c = null;

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        File f = null;

        for(int y = 0; y < height; y++) {

            for(int x = 0; x < width; x++) {

                int blackorwhite = (int)Math.random()*10;

                if(blackorwhite >= 5) {

                    c = Color.BLACK;

                } else if(blackorwhite < 5){

                    c = Color.WHITE;

                }

                img.setRGB(x, y, c.getRGB());

            }

        }

        try {

            f = new File("C:\\Users\\Linus\\Desktop\\Out.png");
            ImageIO.write(img, "png", f);

        } catch (IOException e) {

            System.out.println("Error: " + e);

        }

    }

}

3 Answers3

3

The problem is the precedence of operators. Here :

(int) Math.random() * 10

First you will cast the result of Math.random() to int. Since this method returns values from [0,1), you cast it to int so it is always 0 and then you multiply it by 10 but it is still 0 in the end.

Change your code to :

int blackorwhite = (int) (Math.random() * 10);
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
1

Cast to int after multiply:

(int)(Math.random()*11)

See Random with range

 int range = (max - min) + 1;     
    return (int)(Math.random() * range) + min;
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

While all the answers mentioning operator precedence and the that the cast must be on the complete expression are correct, I like to point out that there is a better option for this specific case:

Use Random.nextInt(int bound) instead.

It returns a pseudo-random number in the range [0...bound>. This method is more efficient and mathematically more correct due to less bias (but I doubt this makes much difference for your use case).

Random random = new Random();

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        int blackorwhite = random.nextInt(10); // Look, no cast

        // Rest of the code as-is
        ...
    }
}

PS: I think your code would be even clearer if you just used nextInt(2) or nextBoolean().

Harald K
  • 26,314
  • 7
  • 65
  • 111