gpt4 book ai didi

java - 密码随机生成器 : creates the same password

转载 作者:行者123 更新时间:2023-12-02 04:09:50 24 4
gpt4 key购买 nike

重点是创建一个密码随机化器,但我的问题是我的代码始终创建相同的密码。我尝试过各种各样的东西,这是我通过互联网获得的最新的东西。

主类:

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());
}
}

Program 类:

import java.util.Random;
public class PasswordRandomizer {
// Define the variables

private Random password = new Random();
private int length;
private String character;

public PasswordRandomizer(int length) {
//creates a new object, uses the given password length
this.length = length;

String characters = "";

Random rndNumbers = new Random();
int randomnumber = 0;


for (int nbr = 1; nbr < length; nbr++) {
randomnumber = rndNumbers.nextInt(25);

char character = "abcdefghijklmnopqrstuvwxyz".charAt(randomnumber);
characters = characters + character;
}

System.out.println(characters);
this.character = characters;
}


public String createPassword() {
// write code that returns a randomized password
PasswordRandomizer randomizer = new PasswordRandomizer(13);
//consists of symbols a-z and is of the length given as a parameter to the constructor
return this.character;
}
}

PasswordRandomizer方法中,有一行System.out.println(characters);每次都会打印出随 secret 码。但是不同的密码不会出现在 createPassword 方法中,只有第一个密码会在输出中始终产生相同的密码。

最佳答案

正如我在评论中提到的,您的方法 createPassword() 调用构造函数并创建一组新的实例变量,这些变量会丢失。将“随机化”代码移至此方法可以解决此问题。查看sample at Ideone 。修改后的构造函数和 createPassword() 代码如下。

public PasswordRandomizer (int length) {
//creates a new object, uses the given password length
this.length = length;

}

public String createPassword() {
String characters = "";

Random rndNumbers = new Random();
int randomnumber = 0;
for (int nbr = 1; nbr < length; nbr++) {
randomnumber = rndNumbers.nextInt(25);
char character = "abcdefghijklmnopqrstuvwxyz".charAt(randomnumber);
characters = characters + character;
}

System.out.println(characters);
return characters;
}

关于java - 密码随机生成器 : creates the same password,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901007/

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