Generating a hexadecimal string

Asked

Viewed 657 times

2

Good afternoon guys, I’m generating a random hexadecimal string in this pattern: 81c1328d-4dae-4af7-9974-893bb8ec90d4

But I would like to optimize this code here:

public String geraKee(){

    String letras = "abcdef0123456789";  

    Random random = new Random();  

    String armazenaChaves = "";  
    int index = -1;  

    for( int i = 0; i < 8; i++ ) {  
       index = random.nextInt( letras.length() );  
       armazenaChaves += letras.substring( index, index + 1 );  
    }
    armazenaChaves += "-";
    for( int i = 0; i < 4; i++ ) {  
       index = random.nextInt( letras.length() );  
       armazenaChaves += letras.substring( index, index + 1 );  
    }
    armazenaChaves += "-4";
    for( int i = 0; i < 3; i++ ) {  
       index = random.nextInt( letras.length() );  
       armazenaChaves += letras.substring( index, index + 1 );  
    }
    armazenaChaves += "-";
    for( int i = 0; i < 4; i++ ) {  
       index = random.nextInt( letras.length() );  
       armazenaChaves += letras.substring( index, index + 1 );  
    }
    armazenaChaves += "-";
    for( int i = 0; i < 12; i++ ) {  
       index = random.nextInt( letras.length() );  
       armazenaChaves += letras.substring( index, index + 1 );  
    }
    return armazenaChaves;  

}
  • 1

    What’s wrong with the code?

  • 1

    No one just thinks he’s unnecessarily big.

1 answer

6


Wouldn’t it be the case to use one UUID.randomUUID() simply?

Example:

import java.util.UUID;

class GerarUUID {
   public static void main(String[] aArgs) {
      UUID id = UUID.randomUUID();
      System.out.println("UUID " + id);
   }
}

Output (at each call comes out a different value as it is random):

UUID 7d7b34ea-7faf-4935-9829-995975751494

See working on IDEONE.

  • Thanks man, I didn’t know this function yet, but it’s exactly what I needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.