我正在制作密码生成器和管理器。我通过从 for 循环一次生成一个字符来创建密码。在每次 for 循环迭代结束时,它会打印出所选的随机字符。我一直在尝试将密码 char 逐个字符存储到与 for 循环中 i 的值相关的数组的索引中。那不仅仅是打印,我什么也做不了。因此我有两个问题,我的主要问题是:是否可以捕获我打印的字符然后将它们存储在字符串中?或者,就像下面的代码一样,我可以避免运行时(通过我的数组)出现的空指针异常吗?当我尝试在索引 i 处将字符串分配给我的密码字符串时,会发生空指针异常。我的代码可能会更好地解释它。谢谢你的帮助 :)
package pass.gen;
public class PassGen {
public static void main(String[] args) {
PassGen passGen = new PassGen();
passGen.generate();
}
String lAlpha = "abcdefghijklmnopqrstuvwxyz"; //used to generate lowercase pass chars
String uAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //used to generate uppercase pass chars
int minNum = 0; //the mininum number that a integer value can be in the password
int maxNum = 9; //the max number "" ...........................................""
int randomNumber;
int minString = 0;
int maxString = 25;
int randomLNum;
int randomUNum;
int low1 = 1;
int high3 = 3;
int ran3;
char randomLChar;
char randomUChar;
char randomNumChar;
String randomLString;
String randomUString;
String randomNumString;
String passString []; //should this be an array of chars?
boolean case1; //if the case is true (case1 is for random numbers) then a random number is added to the passString
boolean case2; //if the case is true (case2 is for random lowercase letters) then a random lowercase letter is added to the passString
boolean case3; //if the case is true (case3 is for random uppercase letters) then a random uppercase letter is added to the passString
void generate(){
for(int i = 0; i < 4; i++){
ran3 = low1 + (int)(Math.random() * ((high3 - low1) + 1));
switch(ran3){
case 1:genNumber(0,9);
break;
case 2:genLAlpha();
break;
case 3:genUAlpha();
break;
default:System.out.println("Unable to Generate a Password.");
}
if(case1 == true){
passString[i] = randomNumString;
}if(case2 == true){
passString[i] = randomLString;
}if(case3 == true){
passString[i] = randomUString;
}
}
System.out.println(passString);
}
void genNumber(int min, int max){
randomNumber = min + (int)(Math.random() * ((max - min) + 1));
randomNumChar = Character.forDigit(randomNumber,5);
case1 = true;
}
void genLAlpha(){
randomLNum = minString + (int)(Math.random() * ((maxString - minString) + 1));
randomLChar = lAlpha.charAt(randomLNum);
randomLString = Character.toString(randomLChar);
case2 = true;
}
void genUAlpha(){
randomUNum = minString + (int)(Math.random() * ((maxString - minString) + 1));
randomUChar = uAlpha.charAt(randomUNum);
randomUString = Character.toString(randomUChar);
case3 = true;
}
}