reset password
Author Message
thewall
Posts: 4
Posted 11:10 Oct 12, 2019 |

Is there a certain way we must generate a string with random letters? Do we use Math.random to generate a 4-digit and turn each digit into a random character or there a simpler, efficient way? Chapter 4 doesn't cover generating random characters. Thank you.

Last edited by thewall at 11:14 Oct 12, 2019.
wcwir
Posts: 75
Posted 11:45 Oct 12, 2019 |

A random 4-digit number wouldn't help you with constructing a random 4-character string. Why? There are only 10 digits, but 26 letters. So you can't include all letters in a digit to letter mapping.

Letters already are mapped to numbers - 'A' is 65, 'B' is 66, and so on till 'Z' is 90, then 'a' is 97, 'b' is 98 and so on until 'z' is 122.

For example:

char c = (char) 81;

will make give c the value 'Q'.

So what you need to do is generate 4 numbers in the appropriate range -- [65, 90] for uppercase and [97, 122] for lowercase -- and then cast them to chars, and then concatenate these four characters to form a string. You already know how to generate a number in a specific [lowerbound, upperbound] range from previous labs.

But you don't need to remember what numbers different characters are mapped to -- you can simply use the characters as in they were numbers!

So: for example if you want to generate a character in range ['j', 't'] you would do this:

(char) ('j' + Math.random() * ('t' - 'j' + 1));

or, if you are using an instance of Random class:

(char)('j' + r.nextInt('t' - 'j' + 1));

 

thewall
Posts: 4
Posted 14:22 Oct 12, 2019 |

Figured it out, thank you!