我编写了这个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;
}
使用浮动和使用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);
}
}
你的split
将生成一个长度为17的数组,开头是一个空字符串。您的生成器偶尔会绘制出第0个元素,这个元素不会影响最终字符串的长度。 (作为副作用,F
永远不会被绘制。)
split
有这种奇怪的行为并使用它:抛弃使用round
的令人讨厌的公式。请使用1 + random.nextInt(16)
作为索引。getRandomColor
时重新创建生成器:这会破坏生成器的统计属性。将random
作为参数传递给getRandomColor
。另外为了确保您的String总是包含6个字符,请尝试用for
替换while
循环。请参阅:
while (color.length() <= 6){
color += letters[random.nextInt(17)];
}