题目要求:
1. 生成一个长度是3的随机字符串,把这个字符串作为当做密码
2. 使用穷举法生成长度是3个字符串,匹配上述生成的密码
要求: 分别使用多层for循环 和 递归解决上述问题
1)首先用递归来实现
public static void guessNum(char[] c, int index, String password){
boolean flag = false;
if (flag) {
return;
}
for (int i = '0'; i <= 'z'; i++) {
if (!Character.isLetterOrDigit(i)) {
continue;
}
c[index] = (char) i;
if (index == c.length - 1) {
String guess = new String(c);
if (guess.equals(password)) {
System.out.println("找到了密码" + guess);
flag = true;
return;
}
}
else {
guessNum(c, index + 1, password);
}
}
}
public static void main(String[] args) {
char[] c = new char[3];
int start = '0';
int end = 'z' + 1;
for (int i = 0; i < c.length; i++) {
while (true) {
char c1 = (char) (Math.random() * (end - start) + start);
if (Character.isLetter(c1) || Character.isDigit(c1)) {
c[i] = c1;
break;
}
}
}
String str1 = new String(c);
System.out.println("随机生成的字符串是:" + str1);
System.out.println("----------");
guessNum(c, 0, str1);
2)下面用多层for循环实现
public static void main(String[] args) {
char[] c = new char[3];
int start = '0';
int end = 'z' + 1;
for (int i = 0; i < c.length; i++) {
while (true) {
char c1 = (char) (Math.random() * (end - start) + start);
if (Character.isLetter(c1) || Character.isDigit(c1)) {
c[i] = c1;
break;
}
}
}
String str1 = new String(c);
System.out.println("随机生成的字符串是:" + str1);
System.out.println("----------");
String result = "";
char[] g = new char[3];
for (int i = '0'; i <= '9'; i++) {
result += (char) i;
}
for (int i = 'a'; i <= 'z'; i++) {
result += (char) i;
}
for (int i = 'A'; i <= 'Z'; i++) {
result += (char) i;
}
for (int i = 0; i < result.length(); i++){
for (int j = 0; j < result.length(); j++){
for (int k = 0; k < result.length(); k++){
g[0] = result.charAt(i);
g[1] = result.charAt(j);
g[2] = result.charAt(k);
String guess = new String(g);
if (str1.equals(guess)) {
System.out.println("找到了密码" + guess);
}
}
}
}
}