import java.util.Scanner;
import java.util.Random;
public class SecretPasscodes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("#########################|Password Generator|#######################");
System.out.println("# [1] Lowercase Letters #");
System.out.println("# [2] Uppercase and Lowercase Letters #");
System.out.println("# [3] Letters and numbers #");
System.out.println("# [4] Lowercase and Uppercase letters, Numbers , and symbols #");
System.out.println("# [5] Quit #");
System.out.println("####################################################################");
System.out.println("Enter your selection(1-5)");
// Variables
int choice = in.nextInt();
System.out.println("Password Length(1-14");
int passLength = in.nextInt();
// Lowercase
if (choice == 1) {
for (int counter = 0; counter < passLength; counter++) {
int lowerLetter = rand.nextInt((122 - 97) + 1) + 97;
System.out.print((char) lowerLetter);
}
// Uppercase + lowercase
} else if (choice == 2) {
for (int counter = 0; counter < passLength; counter++) {
int ascii = rand.nextInt(255);
while ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) {
System.out.print((char) ascii);
}
}
}
}
}
如果删除while循环,for循环将不会是无限的。一旦我添加了while循环,for循环变为无限。我被困在这一段时间,我的apcs老师没有回应。
谢谢!
答案 0 :(得分:2)
你失败的原因是你在进入while循环之前分配了ascii。在while循环中不会更改此值,因此它将始终包含您在进入while循环之前设置的值。您需要更改while条件,或者需要修改while块内的ascii,使其不再符合指定的条件。你也可以在你的写作线后添加休息。 (使它像if语句一样工作)。您的代码可以概括为:
While(1)
{
print(1)
}
答案 1 :(得分:1)
我认为你想做这样的事情:
else if (choice == 2) {
for (int counter = 0; counter < passLength; counter++) {
int ascii = rand.nextInt(255);
while (true) {
if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) {
System.out.print((char) ascii);
break;
} else {
ascii = rand.nextInt(255);
}
}
}
System.out.println();
}