java- how to generate a random hexadecimal value within specified range of values

前端 未结 6 401
广开言路
广开言路 2020-12-16 14:40

I have a scenario in a java web app, where a random hexadecimal value has to be generated. This value should be within a range of values specified by me. (The range of value

6条回答
  •  情歌与酒
    2020-12-16 15:02

    Random progressive hex colors:

    String letters[] = "0123456789ABCDEF".split("");
    int min=letters.length-(letters.length/3);
    int max=letters.length;
    Random rnd=new Random(1000);
    String colorEx[]= new String[]{"00","00","00"};
    int colorChange=0;
    int addColorChange=1;
    
    private String getRandomColor() {
        StringBuilder color = new StringBuilder("#");
        int highColor=rnd.nextInt(2)+1;
        for (int i = 0; i<3; i++) {
            int addColor=0;
            if (i==highColor)
                highColor=min;
    
            color.append(colorEx[i]);
    
            if (colorChange==i) {
                if (colorEx[i].equals("00"))
                    colorEx[i]="55";
                else if (colorEx[i].equals("55"))
                    colorEx[i]="AA";
                else if (colorEx[i].equals("AA"))
                    colorEx[i]="FF";
                else {
                    if (i>0 && !"00".equals(colorEx[i-1]))
                        colorEx[i-1]="00";
                    else if (i<2)
                        colorEx[i+1]="00";
                    colorChange+=addColorChange;
                    //colorChange++;
                    if (colorChange>2 || colorChange<0) {
                        //colorChange=0;
                        addColorChange=-addColorChange;
                        colorChange+=addColorChange;
                        colorChange+=addColorChange;
                    }
                }
            }
        }
        return color.toString();
    }
    

提交回复
热议问题