import java.util.Random;
public class PasswordRandomizer {
// Define the variables
private Random random = new Random();
private int passwordLength;
private String password = "";
public PasswordRandomizer(int length) {
// Initialize the variable
this.passwordLength = length;
}
public String createPassword() {
// write code that returns a randomized password
for(int i = 0; i < this.passwordLength; i++){
int j = random.nextInt();
char symbol = "abcdefghijklmnopqrstuvwxyz".charAt(j);
this.password = this.password + symbol;
}
return this.password;
}
}
如何将字符添加到字符串中,我尝试了此操作,但收到此错误:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -414383904".
最佳答案
因为random.nextInt()
返回 -2,147,483,648 和 2,147,483,647 之间的值。
你想要的是random.nextInt("abcdefghijklmnopqrstuvwxyz".length())
我还会将“abcdefghijklmnopqrstuvwxyz”分配给一个常量。
private final static String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
Char randomChar = ALPHABET.charAt(random.nextInt(ALPHABET.length()));
关于java - 向字符串添加字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26659486/