qum*_*uma 8 java random colors
我编写了这个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;
}
Run Code Online (Sandbox Code Playgroud)
sla*_*dan 22
使用浮动和使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
您split
将生成一个长度为 17 且开头为空字符串的数组。您的生成器偶尔会绘制第零个元素,这不会影响最终字符串的长度。(作为副作用,F
永远不会被绘制。)
接受split
这种奇怪的行为并与之合作:抛弃使用 的令人讨厌的公式round
。1 + random.nextInt(16)
而是用作您的索引。
不要在每次调用getRandomColor
: 时重新创建生成器,这会破坏生成器的统计属性。random
作为参数传递给getRandomColor
.
归档时间: |
|
查看次数: |
7716 次 |
最近记录: |