Java随机颜色字符串

问题描述 投票:7回答:3

我编写了这个java方法但有时颜色String只有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;
}
java random colors
3个回答
17
投票

使用浮动和使用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);
    }

}

2
投票

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

  1. 接受split有这种奇怪的行为并使用它:抛弃使用round的令人讨厌的公式。请使用1 + random.nextInt(16)作为索引。
  2. 不要在每次调用getRandomColor时重新创建生成器:这会破坏生成器的统计属性。将random作为参数传递给getRandomColor

1
投票

另外为了确保您的String总是包含6个字符,请尝试用for替换while循环。请参阅:

while (color.length() <= 6){
    color += letters[random.nextInt(17)];
}
© www.soinside.com 2019 - 2024. All rights reserved.