首页 > 解决方案 > 递归 - 显示错误的尝试次数

问题描述

所以代码工作正常,但是破解 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;
    }
}

标签: javarecursionpasswords

解决方案


您使用的字符集的长度是 62。最后一个字符letters0,因此匹配所需的尝试次数061尝试次数。

因此,即使随机生成的 5 个字母密码包含00000(都是字符集中的最后一个字符。),总尝试次数为61*5,即305. 所以输出永远不会大于这个值。

因此,此代码永远不会返回远高于 3 位数字的值。(我假设您期望 4 或 5 位数字)。此外,它可以返回的最大值是305.

如果您需要更高的尝试次数,请增加密码长度。


推荐阅读