'Trying to print random from the string

Im trying to make the output be something like: 0dd58b9b-6bcd-4727

String id = "ABCDEF1234567890";     
id.charAt(random.nextInt(id.length()));
System.out.println (id.charAt(8) + "-" id.charAt(4)...);


Solution 1:[1]

I understand that your requirement is to Print the random output with something like 8 char- 4 char - 4 char

For this you can use the UUID Java utility itself. Below is the code that will always generate random code

    import java.util.UUID;    
    public class MyClass {
        public static void main(String args[]) {
          UUID uuid=UUID.randomUUID(); 

           //Doing this step since the requirement is 8 char - 4 char- 4char

          String output = uuid.toString().substring(0,18);
          System.out.println(output);    
        }
//This will give output like b673de0c-38b6-4cf1
    }

The logic behind UUID Random generation is explained below

UUID stands for Universally Unique IDentifier. UUIDs are standardized by the Open Software Foundation (OSF). It is a part of the Distributive Computing Environment (DCE). A UUID is 36 characters (128-bit) long unique number. It is also known as a Globally Unique IDentifier (GUID).

enter image description here

Solution 2:[2]

this method will give you the output you want(8characters-4characters-4characters)

static String getRandomFromString(String input) {
    Random random = new Random();
    String result = "";
    for(int i = 0; i < 18; i++) {
        if(i == 8 || i == 13) {
            result += "-";
        }else {
            result += input.charAt(random.nextInt(input.length()));
        }
    }
    return result;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Divya J
Solution 2 tttm