Java Hex Color Code Generator

Last week I got an ideas on a random color generator in Java. One of my friends asked me to implement this logic.

Here is my example hexadecimal color code generate logic.


public Map hexCodeGenerator(int colorCount){
  int maxColorValue = 16777215;
  // this is decimal value of the "FFFFFF"

  int devidedvalue = maxColorValue/colorCount;

  int countValue = 0;

  HashMap hexColorMap = new HashMap();

  for(int a=0; a < colorCount && maxColorValue >= countValue ; a++){
   if(a != 0){
    countValue+=devidedvalue;
    hexColorMap.put(a,Integer.toHexString( 0x10000 | countValue).substring(1).toUpperCase());

   }else{
    hexColorMap.put(a,Integer.toHexString( 0x10000 | countValue).substring(1).toUpperCase());
   }



  }
  return hexColorMap;

 }



Or You can use Math.random also. Here is example using Math.random

public static Map randomCodeGenerator(int colorCount){
  HashMap hexColorMap = new HashMap();
  for(int a=0;a < colorCount; a++){
   String code = ""+(int)(Math.random()*256);
   code = code+code+code;
   int  i = Integer.parseInt(code);

   
   hexColorMap.put(a,Integer.toHexString( 0x1000000 | i).substring(1).toUpperCase());
  }
 return hexColorMap;
 }


help my site stand out :

Comments

elena said…
Good :) It worked !!
elena said…
Nice one !!.. Thanks for the post.
Roshan said…
Thanks..its great...

Popular posts from this blog

Secure Spring Boot REST API using Basic Authentication

Integrating Swagger with Spring Boot REST API

Building a RESTFul Service using Spring Boot