I need to initialize an array of characters with 1000
random characters between [a,..z]
and [A,..,Z]
.
I don’t want do this by first generating only characters between [a,..z]
and then only characters in [A...Z]
but treat all 52 characters equally.
I know one way to do this is to generate a random number between 0 and 51 and assign it one of the character values.
How would I approach this problem or assign values to the random numbers between 0 and 51?
In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.
Use Math. random() function to get the random number between(0-1, 1 exclusive). Multiply it by the array length to get the numbers between(0-arrayLength).
For example, in a dice game possible values can be between 1 to 6 only. Below is the code showing how to generate a random number between 1 and 10 inclusive. Random random = new Random(); int rand = 0; while (true){ rand = random. nextInt(11); if(rand !=
You have got the interesting code idea. Here might be the thought.
array[]
of chars. Best Regards.
Let me give you some general guidelines. The "one way to do this" you mentioned works. I recommend using a HashMap<E>
. You can read more about hashmaps in the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Alternatively, you can use another array that contains a - z and A - Z and you can use the index number to refer to them. But in this case I think it makes more sense to use a HashMap<E>
.
I think you know how to create a Random
object. But if you don't, check out the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
So you basically use the nextInt
method of the Random
class to generate a random number. And you can put that random number into your HashMap
or array. And then you just put that character you get into an array that stores the result of the program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With