【发布时间】:2019-12-19 22:21:52
【问题描述】:
我创建了这个程序,它应该猜出一个 7 个字符的密码。当我运行它时,什么都没有发生。这个程序正确吗?如果有问题,请告诉我要更改的内容。代码如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner inputReal = new Scanner(System.in);
System.out.println("Enter real password (7 characters):");
String realpassword = inputReal.nextLine();
String finalpassword = "";
char real1 = realpassword.charAt(0);
char real2 = realpassword.charAt(1);
char real3 = realpassword.charAt(2);
char real4 = realpassword.charAt(3);
char real5 = realpassword.charAt(4);
char real6 = realpassword.charAt(5);
char real7 = realpassword.charAt(6);
CharSequence avaliableChars = "1234567890qwertyuiopasdfghjklzxcvbnm!@#$%^&*()?";
char guess1;
char guess2;
char guess3;
char guess4;
char guess5;
char guess6;
char guess7;
boolean notFound = true;
while(notFound) {
for(int i1 = 0; i1<47 && notFound == true; i1++) {
guess1 = avaliableChars.charAt(i1);
for(int i2 = 0; i2<47 && notFound == true; i2++) {
guess2 = avaliableChars.charAt(i2);
for(int i3 = 0; i3<47 && notFound == true; i3++) {
guess3 = avaliableChars.charAt(i3);
for(int i4 = 0; i4<47 && notFound == true; i4++) {
guess4 = avaliableChars.charAt(i4);
for(int i5 = 0; i5<47 && notFound == true; i5++) {
guess5 = avaliableChars.charAt(i5);
for(int i6 = 0; i6<47 && notFound == true; i6++) {
guess6 = avaliableChars.charAt(i6);
for(int i7 = 0; i7<47 && notFound == true; i7++) {
guess7 = avaliableChars.charAt(i7);
String guessedpassword = "" + guess1 + guess2 + guess3 + guess4 + guess5 + guess6 + guess7;
if(guessedpassword.equals(realpassword)) {
finalpassword = guessedpassword;
notFound = false;
}
}
}
}
}
}
}
}
}
System.out.println("Guessed password:" + finalpassword);
}
我运行了它,只等了大约 3-5 分钟。输入真实密码后什么也没发生。
【问题讨论】:
-
在最坏的情况下,您正在对最内层循环进行 47^7 次迭代。那是超过 5000 亿次迭代。这需要很长时间才能完成。