java - 递归 - 显示错误的尝试次数
问题描述
所以代码工作正常,但是破解 5 个字母密码的尝试次数不正确。我试过修复东西,但它总是给我 3 位数。尝试的次数应该更高。这是我的代码:
import java.util.Scanner;
import java.util.Random;
class Main {
public static void main(String[] args) {
// Letters for the random generated password
// Variables
String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
Random order = new Random();
int PASSWORD = letters.length();
// While statement to allow user to keep generating passwords
while (true) {
String password = "";
Scanner input = new Scanner(System.in);
// Print/menu
System.out.println("Press 1 to generate a random password");
// Takes user input
int UserOption = input.nextInt();
// If user input equals 1
if (UserOption == 1) {
// Generate a 5-character passwords from the letters in the String
for (int i = 0; i < 5; i++) {
password = password + letters.charAt(order.nextInt(PASSWORD));
}
System.out.println(password);
cracking(5, password, letters, 0, "");
}
// If user input is anything except 1
else {
// Print error
System.out.println("Error");
}
}
}
//Method for cracking password
private static int cracking(int length, String password, String characters, int tries, String tryPass) {
System.out.println(length);
if (length == 0) {
System.out.println("It took " + tries + " tries to crack the password");
return 0;
}
for (int i = 0; i < characters.length(); i++) {
if (password.charAt(length-1) == characters.charAt(i)) {
tryPass = tryPass + characters.charAt(i);
break;
}
tries++;
}
cracking((length-1), password, characters, tries, tryPass);
return 0;
}
}
解决方案
您使用的字符集的长度是 62。最后一个字符letters
是0
,因此匹配所需的尝试次数0
是61
尝试次数。
因此,即使随机生成的 5 个字母密码包含00000
(都是字符集中的最后一个字符。),总尝试次数为61*5
,即305
. 所以输出永远不会大于这个值。
因此,此代码永远不会返回远高于 3 位数字的值。(我假设您期望 4 或 5 位数字)。此外,它可以返回的最大值是305
.
如果您需要更高的尝试次数,请增加密码长度。
推荐阅读
- google-app-engine - Google App Engine 标准 Java8 上的套接字被阻止
- reactjs - 反应调用回调函数无穷大
- bash - 使用 GNU Parallel 并行化嵌套的 for 循环
- angular - 打字稿中的 Angular 6 和 i18n
- jenkins - 如何在不推送新提交的情况下重新启动 GitHub 检查?
- html - 如果复选框的标签是超链接,是否违反 WCAG 2.0 AA?
- reactjs - 'this' 隐含类型为 'any',因为它没有类型注释。在函数上调用绑定时
- swift - Swift 4只旋转一屏UITabBarController
- javascript - 反应 onChange 不从 Div 触发
- c# - Html.EditorFor Post 后不更新