Page 1 of 1

Reputation:

# Generating random upper case letters

Posted 28 March 2010 - 11:15 PM

Hello,

Could someone please explain to how this code works/generates a random character. I especially don't understand the last bit of the code; -(int)'A'+1)

char randomChar =
(char)((int)'A'+Math.random()*((int)'Z'-(int)'A'+1));

Thank you.
Is This A Good Question/Topic? 0

## Replies To: Generating random upper case letters

### #2 mostyfriedman

• The Algorithmi

Reputation: 727
• Posts: 4,473
• Joined: 24-October 08

## Re: Generating random upper case letters

Posted 28 March 2010 - 11:57 PM

Math.random() generates a random double in the interval [0,1.0)..as for ((int)'Z'-(int)'A'+1), this is subtracting the ascii values of 'Z' and 'A'..so now Math.random()*((int)'Z'-(int)'A'+1)) will return a random from 0 to 26..(char)((int)'A'+Math.random()*((int)'Z'-(int)'A'+1)) now the random number generated is added to the ascii value of A and casted to a character..so now you will get a random character between 'A' and 'Z'

Reputation:

## Re: Generating random upper case letters

Posted 29 March 2010 - 12:17 AM

Thanks so much for your help!