我有一种递归生成随机密码的方法,需要至少有一个大写字母。我已经设置了方法,但由于某种原因它告诉我,当我已经在if语句中定义了return
类型时,该方法必须返回String类型。
问题:如何让此错误消失或修复我的方法以使其返回密码?
public static char[]chars = {'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','!','@','$','%','^','&'};
public static String generatePassword(Random rand, String password, int position, int size) //this method must return a result of type String
{
boolean isLowerCase = rand.nextBoolean();
int randomChar = rand.nextInt(chars.length);
char c = chars[randomChar];
if(position == size) //base case
{
return password; //string is returned here?
}
if(isLowerCase)
{
generatePassword(rand, password + c, position + 1, size);
}
else //its either upper or lower case
{
generatePassword(rand, password + Character.toUpperCase(c), position + 1, size);
}
答案 0 :(得分:3)
在所有执行组合的方法中,应该返回一个String。这是你的方法应该是这样的。
public static String generatePassword(Random rand, String password, int position, int size) //this method must return a result of type String
{
boolean isLowerCase = rand.nextBoolean();
int randomChar = rand.nextInt(chars.length);
char c = chars[randomChar];
if(position == size) //base case
{
return password; //string is returned here?
}
if(isLowerCase)
{
return generatePassword(rand, password + c, position + 1, size);
}
else //its either upper or lower case
{
return generatePassword(rand, password + Character.toUpperCase(c), position + 1, size);
}
}
答案 1 :(得分:1)
对我来说这似乎是递归解决方案的一个不好的地方,我建议您使用StringBuilder
和单static Random
。以及方法的单个size
参数。像,
private static Random rand = new Random();
public static String generatePassword(int size) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
int randomChar = rand.nextInt(chars.length);
char ch = chars[randomChar];
if (Character.isLetter(ch)) {
if (rand.nextBoolean()) {
ch = Character.toUpperCase(ch);
}
}
sb.append(ch);
}
return sb.toString();
}