[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1446
  • Last Modified:

How to generate random characters and letters in JAVA

Hello

I have the following function

which generates alphabetic letter + dot so output looks like this B.

I need it to generate 5 random letters + 2 random numbers + dot

how can i achieve this without altering the code too much?
private String fnam1 = (char)((int)'A'+Math.random()*((int)'Z'-(int)'A'+1))+ ".";

Open in new window

0
Maranellas
Asked:
Maranellas
1 Solution
 
arevuriCommented:
You need to get random characters five times and get random number of 2 digit length and then the 5 random characters with 2 digit number and dot.
 
if the the number of character and number and the order is not mandatory, you can try below one


UUID uuid = UUID.randomUUID();
String myRandom = uuid.toString();
System.out.println(myRandom.substring(0,7));
0
 
ioantonCommented:
Try this:

            Random rnd = new Random();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < 8; i++) {
                  buffer.append(Character.toString(i < 5 ? ((char) ('A' + rnd.nextInt('Z' - 'A' + 1))) : ((i < 7) ? (char) ('0' + rnd.nextInt(9)) : '.')));
            }

            String fnam1 = buffer.toString();
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now