GENERATING RANDOM NUMBERS IN JAVA

Hi Fellows, in my previous post (GENERATING UNIQUE RANDOM STRING AND ITS APPLICATION) , I blogged about generating random numbers in VB.net.

Below is its version in JAVA. Enjoy !!!

private String generateRandom(Integer key) {

StringBuffer randomString = new StringBuffer();

String letters = “abcdefghijklmnopqrstuvwxyz“;

String numbers = “0123456789“;

char[] numbersArray = numbers.toCharArray();

char[] lettersArray = letters.toCharArray();

Integer arrIndex = -1;

 

for (int i = 0; i <= key; i++) {

//generate any random number from 1 -100, if them number is even,

//pick a letter randomly else pick a number

int rnd = new Random().nextInt(100);

if (rnd % 2 == 0) {

arrIndex = new Random().nextInt(24);

randomString.append(lettersArray[arrIndex]);

} else {

arrIndex = new Random().nextInt(10);

randomString.append(numbersArray[arrIndex]);

}

}

return randomString.toString();

}

Below is a sample generated strings when application is run.

Advertisements

2 thoughts on “GENERATING RANDOM NUMBERS IN JAVA

  1. Hey, I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say GREAT blog!…..I”ll be checking in on a regularly now….Keep up the good work! 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s