简体   繁体   English

如何在给定一系列值的情况下生成随机字符?

[英]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?例如,我有一个 char 变量direction ,它可以具有“R”、“U”、“L”、“D”等值,如何从这四个中生成随机值?

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) .我将创建一个值为RULDString ,并使用ThreadLocalRandom.nextInt(int)随机选择一个字符。 Something like,就像是,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM