字符串中4个字符的随机密码



我编写了一个代码,它给出了字符串的所有可能的4个字符组合。现在我需要制作一个程序,选择一个随机组合作为密码,然后遍历每个可能的组合,直到找到所选的那个,然后告诉我猜了多少次才找到正确的那个。这是我目前所看到的:

String alphabet = "ABCabc012!";
char pw[] = alphabet.toCharArray();

for (int i = 0; i < pw.length ; i++) {
for (int j = 0; j < pw.length ; j++) {
for (int k = 0; k < pw.length ; k++) {
for (int l = 0; l < pw.length ; l++) {
System.out.println(pw[i] + " " + pw[j] + " " + pw[k] + " " + pw[l]);
}
}
}
}

我尝试将pw[]存储在一个数组中,但我不知道确切的方法。

您真的需要事先将值存储在列表中吗?您是否需要只生成一次每个值,或者这并不重要?

如果你能生成大小为4n次的随机密码,你可以尝试这样做:

public class RandomPass {
static Random random = new Random();
public static void main(String[] args) {
String alphabet = "ABCabc012!";
String password = generatePassword(4, alphabet);
System.out.println("PW is: " + password);
int counter = 0;
while (!generatePassword(4, alphabet).equals(password)) {
counter++;
}
System.out.println("It took: " + counter + " times.");
}
private static String generatePassword(int size, String alphabet) {
StringBuilder pw = new StringBuilder();
for (int i = 0; i < size; i++) {
pw.append(alphabet.charAt(random.nextInt(0, alphabet.length())));
}
return pw.toString();
}

}

如果你真的需要存储它们,那么就把它们存储在ArrayList中,而不是像你在代码中那样打印它们。

之后,你可以遍历数组列表并在其中搜索你的密码。

你真的很接近了!

下面是如何构建组合,将它们添加到ArrayList中,输出它们,从列表中随机选择一个密码,然后随机生成密码,直到得到匹配:

public static void main(String[] args) {
String alphabet = "ABCabc012!";
char pw[] = alphabet.toCharArray();
// generate the combinations
ArrayList<String> combos = new ArrayList<>();
for (int i = 0; i < pw.length ; i++) {
for (int j = 0; j < pw.length ; j++) {
for (int k = 0; k < pw.length ; k++) {
for (int l = 0; l < pw.length ; l++) {
String pwCombo = "" + pw[i] + pw[j] + pw[k] + pw[l];
combos.add(pwCombo);
}
}
}
}
// output the combinations
for(String password : combos) {
System.out.println(password);
}
// pick a random passwrod
Random r = new Random();    
int index = r.nextInt(combos.size());
String pwToGuess = combos.get(index);
System.out.println("Password to guess: " + pwToGuess);
// randomly generate a password until it matches
int tries = 0;
String pwGuess = "";
do {
tries++;
pwGuess = "" + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)];
} while (!pwGuess.equals(pwToGuess));
System.out.println("It took " + tries + " tries to guess the password!");
}

最新更新