有没有办法用Java递归检查一个字符串是否至少包含一个大写字母?

时间:2020-02-21 12:59:13

标签: java string recursion boolean

我可能因为$students = Get-ADGroupMember -Identity "Students" -Filter "objectClass -eq 'user'" | Get-ADUser -Properties DisplayName, extensionAttribute11 | Where-Object { $_.extensionAttribute11 -like '*' } Select-Object DisplayName, @{Name = 'CardNumber'; Expression = { $_.extensionAttribute11}} # display on screen $students # write to new CSV file $students | Export-Csv -Path 'PathToYourOutputCsvFile' -UseCulture -Encoding UTF8 -NoTypeInformation 方法而获得了IndexOutOfBoundsException异常,但是我被卡住了。 我知道我必须使用charAt,但不确定确切的位置。

isUpperCase

2 个答案:

答案 0 :(得分:1)

您必须具有递归的中断条件才能最终出来。您的代码中缺少该条件,并且当字符串的长度为1时,您将获得异常。

在调用isUpperCase之前尝试检查String的长度。

public static boolean hasCapitals(String s) {
    if(s == null || s.length() == 0) {
        return false;
    }
    if(Character.isUpperCase(s.charAt(0))) {
        return true;
    } else if(s.length() > 1){
        return hasCapitals(s.substring(1));
    } else {
        return false;
    }
}

答案 1 :(得分:0)

像这样尝试,正是您需要的

public static void main(String[] args) {
    System.out.println( hasCapitals( "New Hampshire", 0 ) );
    System.out.println( hasCapitals( "word", 0 ) );
    System.out.println( hasCapitals( "I", 0 ) );
    System.out.println( hasCapitals( "", 0 ) );
    System.out.println( hasCapitals( "hamPshire", 0 ) );
}

private static boolean hasCapitals(String value, int index) {
    if(value.isEmpty()) {
        return false;
    }

    if(Character.isUpperCase(value.charAt(index))) {
        return true;
    } else if(value.length() > (index + 1)) {
        return hasCapitals(value, index + 1);
    } 

    return false;

}
相关问题