我编写了这个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)
呢? - Thomascolor += letters[random.nextInt(letters.length)];
代替color += letters[Math.round(random.nextFloat() * 15)];
。 - Manindar