gpt4 book ai didi

java - 方法不允许返回字符串

转载 作者:搜寻专家 更新时间:2023-11-01 02:42:42 24 4
gpt4 key购买 nike

我有一个递归生成随 secret 码的方法,要求至少有一个大写字母。我已经设置了方法,但出于某种原因,当我已经在我的 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);
}

最佳答案

在您的所有执行组合的方法中,应该返回一个字符串。您的方法应如下所示。

    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);
}
}

关于java - 方法不允许返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com