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

GENERATING UNIQUE RANDOM STRING AND ITS APPLICATION

Generating random numbers can be sometimes frustrating, especially when you want them to be unique.

Example in this instance is when you give users unique usernames when they register with you websites.

Below is a simple function to generate random numbers. To make these generated random strings unique (for the purpose of your application you can add the row index, when inserting it into a database, to make it unique. In this case you will be generating always unique random variables)

Function Generate() As String
‘key_chars, is the length of random numbers u want to generate

Dim i_key As Integer

Dim RandomNo As Single
Dim arrIndex As Int16

Dim sb As New StringBuilder

Dim RandomLetter As String

lstLetters = "abcdefghijklmnopqrstuvwxyz"

lstNumber = "0123456789"

LettersArray = Me.Key_Letters.ToCharArray

NumbersArray = Me.lstNumber.ToCharArray


For i_key = 1 To Key_Chars

Randomize()

RandomNo = Rnd()

arrIndex = -1 ‘the number 101 was randomly chosen

If (CType(Random1 * 101, Integer)) Mod 2 = 0 Then

‘if the number generated from the if condition is even get a letter else get a number

‘ generate a random number from the letters array


Do While arrIndex < 0

arrIndex = Convert.ToInt16(LettersArray.GetUpperBound(0) * RandomNo)

Loop

RandomLetter = LettersArray(arrIndex)

sb.Append(RandomLetter)

Else

Do
While arrIndex < 0

arrIndex = Convert.ToInt16(NumbersArray.GetUpperBound(0) * RandomNo)

Loop

RandomLetter = NumbersArray(arrIndex)

sb.Append(RandomLetter)

EndIf

Next

Return sb.ToString

End Function