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)...);
CodePudding user response:
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).
CodePudding user response:
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;
}