Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Random Color String

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;
}
like image 686
quma Avatar asked Feb 17 '16 14:02

quma


People also ask

How do you randomize colors in Java?

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.

Can you randomize strings in Java?

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.


2 Answers

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);
    }

}
like image 71
slartidan Avatar answered Sep 29 '22 23:09

slartidan


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.)

  1. 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.

  2. Don't recreate the generator on each call of getRandomColor: that ruins the generator's statistical properties. Pass random as a parameter to getRandomColor.

like image 29
Bathsheba Avatar answered Sep 29 '22 23:09

Bathsheba