gpt4 book ai didi

java - 有没有一种方法可以用java递归地检查字符串是否至少包含一个大写字母?

转载 作者:行者123 更新时间:2023-12-02 08:58:30 26 4
gpt4 key购买 nike

我收到 IndexOutOfBoundsException 异常可能是因为 charAt 方法,但我被卡住了。我知道我必须使用 isUpperCase 但我不确定具体在哪里。

public static boolean hasCapitals(String s) {
if(Character.isUpperCase(s.charAt(0))) {
return true;
} else {
return hasCapitals(s.substring(1));
}
}

public static void main( String[] args ){
System.out.println( hasCapitals( "New Hampshire" ) ); // returns true
System.out.println( hasCapitals( "word" ) ); // returns false
System.out.println( hasCapitals( "I" ) ); // returns true
System.out.println( hasCapitals( "" ) ); // returns false
}

最佳答案

你必须在递归中有一个中断条件才能最终出来。您的代码中缺少该条件,并且当字符串长度为 1 时您会收到异常。

在调用 isUpperCase 之前尝试检查字符串的长度。

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

关于java - 有没有一种方法可以用java递归地检查字符串是否至少包含一个大写字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339169/

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