是否有在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
)然后用它来映射到炭
。如果你有一个特定的字母表,那么这样的东西很漂亮:
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屋!