是否有在 Java 中生成随机字符的功能? [英] Is there functionality to generate a random character in Java?
问题描述
Java 是否具有生成随机字符或字符串的功能?还是必须简单地选择一个随机整数并将该整数的 ascii 代码转换为字符?
Does Java have any functionality to generate random characters or strings? Or must one simply pick a random integer and convert that integer's ascii code to a character?
推荐答案
有很多方法可以做到这一点,但是是的,它涉及生成一个随机的 int
(例如使用 java.util.Random.nextInt
)然后使用它来映射到 char
.如果你有一个特定的字母表,那么像这样的东西很不错:
There are many ways to do this, but yes, it involves generating a random int
(using e.g. java.util.Random.nextInt
) and then using that to map to a char
. If you have a specific alphabet, then something like this is nifty:
import java.util.Random;
//...
Random r = new Random();
String alphabet = "123xyz";
for (int i = 0; i < 50; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
} // prints 50 random characters from alphabet
<小时>
请注意,java.util.Random
实际上是一个 伪-随机数生成器基于相当弱的线性同余公式.你提到了密码学的必要性;在这种情况下,您可能想要调查使用更强大的密码安全伪随机数生成器(例如java.security.SecureRandom
).
Do note that java.util.Random
is actually a pseudo-random number generator based on the rather weak linear congruence formula. You mentioned the need for cryptography; you may want to investigate the use of a much stronger cryptographically secure pseudorandom number generator in that case (e.g. java.security.SecureRandom
).
这篇关于是否有在 Java 中生成随机字符的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!