【发布时间】: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)];