import java.util.Random;
import java.util.Scanner;
public class PassGen {
public static void main(String[] args) {
String[] characters = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
StringBuilder b = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter password length.");
int length = scan.nextInt();
while (length > 20 || length < 6) {
System.out.println("Password must be between 6 and 20 characters long.");
length = scan.nextInt();
}
Random rand = new Random();
for (int i = 0; i <= length; i++) {
int x = rand.nextInt(characters.length) + 1;
b = new StringBuilder(length + 1);
String s = characters[x];
b.append(s);
}
System.out.println("Your password is: " + b.toString());
}
}
出于某种原因,当我运行这个程序时,它只会在显示一个随机字符之前运行一次for循环,而不管输入的长度如何。
答案 0 :(得分:2)
不,循环正在运行多次迭代 - 但在每次迭代时,您正在创建一个新的StringBuilder:
// This is inside the loop, but should be outside.
b = new StringBuilder(length + 1);
注意有时,我希望循环抛出一个异常 - 如果没有,你最终会得到一个比你想要的更长的字符串。基本上,你有三个一个一个错误...你应该有:
b = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int x = rand.nextInt(characters.length);
b.append(characters[x]);
}
另请注意,如果您只使用字符串而不是字符串数组并使用charAt
,那会更简单:
String characters = "ABCDE...9";
...
int x = rand.nextInt(characters.length());
b.append(characters.charAt(x));
答案 1 :(得分:0)
b = new StringBuilder(length + 1);
需要在for循环之外。您拥有它的方式,每次运行for循环时都会创建b
。
答案 2 :(得分:0)
您总是在循环中重新创建b
对象。它将始终只包含一个字符。