【问题标题】:Java Random Color StringJava 随机颜色字符串
【发布时间】:2016-05-29 07:40:23
【问题描述】:

我已经编写了这个 java 方法,但有时颜色字符串只有 5 个字符长。有谁知道为什么?

@Test
public void getRandomColorTest() {
    for (int i = 0; i < 20; i++) {
        final String s = getRandomColor();
        System.out.println("-> " + s);
    }
}

 public String getRandomColor() {
    final Random random = new Random();
    final String[] letters = "0123456789ABCDEF".split("");
    String color = "#";
    for (int i = 0; i < 6; i++) {
        color += letters[Math.round(random.nextFloat() * 15)];
    }
    return color;
}

【问题讨论】:

  • 为什么不用random.nextInt(16) 而不是Math.round(random.nextFloat() * 15)
  • color += letters[random.nextInt(letters.length)];代替color += letters[Math.round(random.nextFloat() * 15)];

标签: java random colors


【解决方案1】:

使用浮点数和使用round 不是创建此类随机颜色的安全方法。

实际上,颜色代码是十六进制格式的整数。您可以像这样轻松创建这样的数字:

import java.util.Random;

public class R {

    public static void main(String[] args) {

        // create random object - reuse this as often as possible
        Random random = new Random();

        // create a big random number - maximum is ffffff (hex) = 16777215 (dez)
        int nextInt = random.nextInt(0xffffff + 1);

        // format it as hexadecimal string (with hashtag and leading zeros)
        String colorCode = String.format("#%06x", nextInt);

        // print it
        System.out.println(colorCode);
    }

}

【讨论】:

  • 加一个,用于花时间了解 OP 真正想要什么并提交更好的方法。
  • 这就像复制/粘贴一样简单,而且效果很好。谢谢!
【解决方案2】:

您的split 将生成一个长度为 17 的数组,开头为空字符串。您的生成器偶尔会绘制不会影响最终字符串长度的第零个元素。 (作为副作用,F 永远不会被绘制。)

  1. 接受split 的奇怪行为并加以处理:抛弃使用round 的讨厌公式。请改用1 + random.nextInt(16) 作为您的索引。

  2. 不要在每次调用 getRandomColor 时重新创建生成器:这会破坏生成器的统计属性。将random 作为参数传递给getRandomColor

【讨论】:

  • 但是nextFloat 生成一个从 0 到 1 的数字,因此你永远不应该得到 15.5 甚至 16 的乘法。顺便提一句。这不应该把索引抛出边界吗?
  • @ctst:哎呀,split 的行为在我的脑海中出现了错误,并发明了一个适合的答案。现在是正确的。
【解决方案3】:

还要确保您的字符串始终包含 6 个字符,请尝试将 for 循环替换为 while。请看:

while (color.length() <= 6){
    color += letters[random.nextInt(17)];
}

【讨论】:

  • 应该是random.nextInt(16)
猜你喜欢
  • 2021-03-16
  • 2016-02-20
  • 2015-01-31
  • 2018-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多