gpt4 book ai didi

java - 使用子字符串进行随机化

转载 作者:行者123 更新时间:2023-12-02 03:46:35 24 4
gpt4 key购买 nike

我这里的代码只能随机化长度,我需要随机化我的类 createPassword 中的字符串。但是不存在随机化字符串的方法,只能随机化整数。有人有什么建议吗?

主要:

public class Program {
public static void main(String[] args) {
PasswordRandomizer randomizer = new PasswordRandomizer(13);
System.out.println("Password: " + randomizer.createPassword());
System.out.println("Password: " + randomizer.createPassword());
System.out.println("Password: " + randomizer.createPassword());
System.out.println("Password: " + randomizer.createPassword());
}
}

类(class):

import java.util.Random;

public class PasswordRandomizer {
private Random random = new Random();
private int length;

public PasswordRandomizer(int length) {
this.length=length;
random = new Random();
}

public String createPassword() {
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int randomCharIndex = random.nextInt(length);
String randomstr = alphabet.substring(randomCharIndex);
return randomstr;
}
}

输出示例:

Password: ghijklmnopqrstuvwxyz
Password: lmnopqrstuvwxyz
Password: jklmnopqrstuvwxyz
Password: ijklmnopqrstuvwxyz

最佳答案

这会很好地工作:

    public String createPassword() {
StringBuilder pass = new StringBuilder();
Random r = new Random();

for(int i = 0 ; i < length ; i++) {
pass.append( (char)('a' + r.nextInt('z'-'a')) );
}
return pass.toString();
}

这个想法是利用char可以用作int并转换回char(并且字母字符是连续的)以 ASCII 码表示)。所以你用它来获得一个随机字符:
minimumValue + random.nextInt(MaxValue-MinValue)

关于java - 使用子字符串进行随机化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com