【问题标题】:I wanted to make an random image generator but it does not work我想制作一个随机图像生成器,但它不起作用
【发布时间】:2019-06-30 14:32:16
【问题描述】:

所以我制作了这个程序,我希望它创建一个只有黑白的 8 x 8 大小的图像,但它只显示白色而不是随机分布的黑白。这是我的代码。如果有人可以提供帮助,那就太好了: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);

        }

    }

}

【问题讨论】:

    标签: java bufferedimage


    【解决方案1】:

    问题在于运算符的优先级。这里:

    (int) Math.random() * 10
    

    首先,您将Math.random() 的结果转换为int。由于此方法从[0,1) 返回值,因此将其转换为int,因此它始终为0,然后将其乘以10,但最终仍为0。

    将您的代码更改为:

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

    【讨论】:

    • @GamingEngine 如果有帮助,请接受答案
    【解决方案2】:

    乘法后转换为 int:

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

    Random with range

     int range = (max - min) + 1;     
        return (int)(Math.random() * range) + min;
    

    【讨论】:

      【解决方案3】:

      虽然所有提到运算符优先级和强制转换必须在完整表达式上的答案都是正确的,但我想指出对于这种特定情况有更好的选择:

      请改用Random.nextInt(int bound)

      它返回[0...bound&gt; 范围内的伪随机数。由于偏差较小,此方法为 more efficient and mathematically more correct(但我怀疑这对您的用例有很大影响)。

      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:我认为如果您只使用nextInt(2)nextBoolean(),您的代码会更清晰。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        • 2022-07-07
        • 2023-01-21
        • 2021-09-11
        • 2013-02-17
        • 2020-04-07
        相关资源
        最近更新 更多