我的作业是用递归方法来破解给定长度的密码,n(无限且未知!)由小英文字母(a-z)组成。
这是创建随机密码的“Password”类:
import java.util.Random;
public class Password {
private String _password = "";
public Password(int length) {
Random generator = new Random();
for (int i = 0; i < length; ++i) {
this._password = this._password + (char) (generator.nextInt(26) + 97);
}
}
public boolean isPassword(String st) {
return st.equals(this._password);
}
public String getPassword() {
return this._password;
}
}
这是详细问题:
“你必须写一个静态递归方法,
public static String findPassword(Password p, int length)
“破解”代码。
这是一个 main 方法的示例:
public class Main {
public static void main(String[] args) {
Password p = new Password(5);
System.out.println(p.getPassword());
System.out.println(Ex14.findPassword(p, 5));
}
}
重要笔记:
- 该方法必须是递归的,不使用任何循环。
- 您不能使用 getPassword 方法。
- 如果您想使用 String 类的方法,您可以only使用以下内容:charAt、子字符串、等于、长度。
- 您可以使用重载,但不能使用其他方法。 (不能使用 String.replace/String.replaceall)
- 您不能使用静态(全局)变量。
- 您不能使用任何数组。 ”
这是我到目前为止所拥有的,这显然不起作用; :\
public static String findPassword(Password p, int length) {
return findPassword(p, length, "", 'a');
}
public static String findPassword(Password p, int length, String testPass, char charToChange) {
int currDig = testPass.length() - 1;
if (p.isPassword(testPass))
return testPass;
if (length == 0) // There is no password.
return ""; // Returns null and not 0 because 0 is a password.
if (length > testPass.length())
return findPassword(p, length, testPass + charToChange, charToChange);
if (testPass.length() == length) {
//TODO if charToChange is 'z', then make it the one before it '++', and reset everything else to a.
//if (charToChange == 'z') {
// charToChange = 'a';
// String newString = testPass.substring(0, currDig-1) +
// (charToChange++)
// +testPass.substring(currDig+1,testPass.length()-1);
System.out.println("it's z");
// TODO currDig --;
// String newerString = testPass.substring(0, currDig - 1)
// + (char) (testPass.charAt(testPass.length() - 1) - 25);
// currDig--;
}
return "";
}
非常感谢!非常感激!
- 三重S