dook
dook

Reputation: 17

How can I generate random characters given a range of values?

For example I have a char variable direction that can have values such as "R", "U", "L", "D", how do I generate random values from these four?

Upvotes: 0

Views: 190

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

There are a number of approaches you could take. I would create a String with the value of RULD and pick a character at random using ThreadLocalRandom.nextInt(int). Something like,

Random rand = ThreadLocalRandom.current();
String directions = "RULD";
System.out.println(directions.charAt(rand.nextInt(directions.length())));

Upvotes: 2

Related Questions