I have written this java method but sometimes the color String is only 5 characters long. Does anyone know why?
@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 rand = new Random(); As colours are separated into red green and blue, you can create a new random colour by creating random primary colours: // Java 'Color' class takes 3 floats, from 0 to 1. float r = rand.
You can also generate a random alphanumeric string of fixed length using streams in Java. A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters.
Working with floats and using round
is not a safe way of creating such random colors.
Actually a color code is an integer in hexadecimal formatting. You can easily create such numbers like this:
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);
}
}
Your split
will generate an array of length 17 with an empty string at the beginning. Your generator occasionally draws that zeroth element which will not contribute to the length of the final string. (As a side effect, F
will never be drawn.)
Accept that split
has that odd behaviour and work with it: Ditch that nasty formula that uses round
. Use 1 + random.nextInt(16)
instead as your index.
Don't recreate the generator on each call of getRandomColor
: that ruins the generator's statistical properties. Pass random
as a parameter to getRandomColor
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With