java随机生成二进制_有在Java中生成随机字符的功能吗?

有在Java中生成随机字符的功能吗?

Java是否具有生成随机字符或字符串的功能? 还是必须简单地选择一个随机整数并将该整数的ASCII码转换为字符?

Chris asked 2020-01-08T02:08:52Z

16个解决方案

117 votes

要在a-z中生成随机字符:

Random r = new Random();

char c = (char)(r.nextInt(26) + 'a');

dogbane answered 2020-01-08T02:09:26Z

81 votes

有很多方法可以做到这一点,但是可以,它涉及到生成一个随机的java.security.SecureRandom(例如使用java.security.SecureRandom),然后使用它映射到char。如果您有一个特定的字母,那么这样的做法很不错:

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.security.SecureRandom实际上是基于相当弱的线性同余公式的伪随机数生成器。 您提到了加密的需求; 您可能想研究在这种情况下使用功能更强大的加密安全伪随机数生成器(例如java.security.SecureRandom)。

polygenelubricants answered 2020-01-08T02:09:07Z

68 votes

您还可以使用Apache Commons项目中的RandomStringUtils:

RandomStringUtils.randomAlphabetic(stringLength);

Josema answered 2020-01-08T02:09:46Z

10 votes

private static char rndChar () {

int rnd = (int) (Math.random() * 52); // or use Random or whatever

char base = (rnd < 26) ? 'A' : 'a';

return (char) (base + rnd % 26);

}

生成范围a-z,A-Z的值。

Peter Walser answered 2020-01-08T02:10:06Z

4 votes

String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

char letter = abc.charAt(rd.nextInt(abc.length()));

这个也很好。

Ricardo Vallejo answered 2020-01-08T02:10:26Z

3 votes

在下面的97 ascii值中有一个小的“ a”。

public static char randomSeriesForThreeCharacter() {

Random r = new Random();

char random_3_Char = (char) (97 + r.nextInt(3));

return random_3_Char;

}

在上面的3个数字中,将a,b,c或d替换为数字,如果您希望将所有字符都从a转换为z,则将3替换为25。

duggu answered 2020-01-08T02:10:50Z

1 votes

您可以使用基于Quickcheck规范的测试框架中的生成器。

要创建随机字符串,请使用anyString方法。

String x = anyString();

您可以使用一组更受限的字符或具有最小/最大大小限制的字符串来创建字符串。

通常,您将使用多个值运行测试:

@Test

public void myTest() {

for (List any : someLists(integers())) {

//A test executed with integer lists

}

}

Thomas Jung answered 2020-01-08T02:11:23Z

1 votes

使用美元:

Iterable chars = $('a', 'z'); // 'a', 'b', c, d .. z

给定String,您可以构建“改组”的字符范围:

Iterable shuffledChars = $('a', 'z').shuffle();

然后取前两个String个字符,您将得到一个随机字符串,长度为m。最终代码很简单:

public String randomString(int n) {

return $('a', 'z').shuffle().slice(n).toString();

}

注意:条件String由m检查

编辑

正如史蒂夫(Steve)正确指出的那样,String每个字母最多使用一次。 解决方法您可以在致电shuffle之前重复输入m字母:

public String randomStringWithRepetitions(int n) {

return $('a', 'z').repeat(10).shuffle().slice(n).toString();

}

或只提供您的字母为String:

public String randomStringFromAlphabet(String alphabet, int n) {

return $(alphabet).shuffle().slice(n).toString();

}

String s = randomStringFromAlphabet("00001111", 4);

dfa answered 2020-01-08T02:12:09Z

1 votes

尝试这个..

public static String generateCode() {

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

String fullalphabet = alphabet + alphabet.toLowerCase() + "123456789";

Random random = new Random();

char code = fullalphabet.charAt(random.nextInt(9));

return Character.toString(code);

}

Sebo Molnár answered 2020-01-08T02:12:29Z

1 votes

这是一个简单但有用的发现。 它定义了一个名为RandomCharacter的类,该类具有5个重载方法以随机获取某种类型的字符。 您可以在以后的项目中使用这些方法。

public class RandomCharacter {

/** Generate a random character between ch1 and ch2 */

public static char getRandomCharacter(char ch1, char ch2) {

return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));

}

/** Generate a random lowercase letter */

public static char getRandomLowerCaseLetter() {

return getRandomCharacter('a', 'z');

}

/** Generate a random uppercase letter */

public static char getRandomUpperCaseLetter() {

return getRandomCharacter('A', 'Z');

}

/** Generate a random digit character */

public static char getRandomDigitCharacter() {

return getRandomCharacter('0', '9');

}

/** Generate a random character */

public static char getRandomCharacter() {

return getRandomCharacter('\u0000', '\uFFFF');

}

}

为了演示其工作原理,让我们看一下下面的测试程序,该程序显示175个随机的小写字母。

public class TestRandomCharacter {

/** Main method */

public static void main(String[] args) {

final int NUMBER_OF_CHARS = 175;

final int CHARS_PER_LINE = 25;

// Print random characters between 'a' and 'z', 25 chars per line

for (int i = 0; i < NUMBER_OF_CHARS; i++) {

char ch = RandomCharacter.getRandomLowerCaseLetter();

if ((i + 1) % CHARS_PER_LINE == 0)

System.out.println(ch);

else

System.out.print(ch);

}

}

}

输出为:

fXsYB.png

如果您再次运行一次:

RhIrV.png

我要感谢Y.Daniel Liang的书《 Java编程简介,综合版,第10版》,在其中我引用了这些知识并在我的项目中使用了这些知识。

注意:如果您不熟悉重载的方法,则简而言之,方法重载是一项功能,如果一个类的参数列表不同,则它允许一个类拥有多个具有相同名称的方法。

Gulbala Salamov answered 2020-01-08T02:13:12Z

0 votes

看一下Java Randomizer类。我认为您可以使用randomize(char [] array)方法将字符随机化。

manuel answered 2020-01-08T02:13:32Z

0 votes

我的建议是生成带有混合大小写的随机字符串,例如:“ DthJwMvsTyu”。

当其代码2692943274603603709440(97至122)和2692943274603709709441(65至90)的第5位(2 ^ 5或1 << 5或32)不同时,该算法基于字母的ASCII码。

A:结果为0或1。

A:结果为0或32。

较高的2692943274603709709440为65,较低的a为97。差异仅在第5位(32)上,因此为了生成随机字符,我们执行二进制OR'|' 随机2692943274603603709442(0或32)和随机代码A至Z(65至90)。

public String fastestRandomStringWithMixedCase(int length) {

Random random = new Random();

final int alphabetLength = 'Z' - 'A' + 1;

StringBuilder result = new StringBuilder(length);

while (result.length() < length) {

final char charCaseBit = (char) (random.nextInt(2) << 5);

result.append((char) (charCaseBit | ('A' + random.nextInt(alphabetLength))));

}

return result.toString();

}

Marcin Programista answered 2020-01-08T02:14:10Z

0 votes

这是生成随机字母数字代码的代码。 首先,必须声明一串允许包含在随机数中的字符,并定义字符串的最大长度

SecureRandom secureRandom = new SecureRandom();

String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";

StringBuilder generatedString= new StringBuilder();

for (int i = 0; i < MAXIMUM_LENGTH; i++) {

int randonSequence = secureRandom .nextInt(CHARACTERS.length());

generatedString.append(CHARACTERS.charAt(randonSequence));

}

使用toString()方法从StringBuilder获取字符串

Abhishek Jha answered 2020-01-08T02:14:34Z

0 votes

如果只想生成十六进制值,polygenelubricants的答案也是一个很好的解决方案:

/** A list of all valid hexadecimal characters. */

private static char[] HEX_VALUES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F' };

/** Random number generator to be used to create random chars. */

private static Random RANDOM = new SecureRandom();

/**

* Creates a number of random hexadecimal characters.

*

* @param nValues the amount of characters to generate

*

* @return an array containing nValues hex chars

*/

public static char[] createRandomHexValues(int nValues) {

char[] ret = new char[nValues];

for (int i = 0; i < nValues; i++) {

ret[i] = HEX_VALUES[RANDOM.nextInt(HEX_VALUES.length)];

}

return ret;

}

schnatterer answered 2020-01-08T02:14:54Z

-1 votes

如果您不介意在代码中添加新库,则可以使用MockNeat生成字符(免责声明:我是作者之一)。

MockNeat mock = MockNeat.threadLocal();

Character chr = mock.chars().val();

Character lowerLetter = mock.chars().lowerLetters().val();

Character upperLetter = mock.chars().upperLetters().val();

Character digit = mock.chars().digits().val();

Character hex = mock.chars().hex().val();

Andrei Ciobanu answered 2020-01-08T02:15:14Z

-2 votes

Random randomGenerator = new Random();

int i = randomGenerator.nextInt(256);

System.out.println((char)i);

假设您将'0,'1','2'..视为字符,应该照顾好自己想要的东西。

ring bearer answered 2020-01-08T02:15:34Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值