[英]Is there a way to check if a string contains at least one capital letter recursively with java?
I get IndexOutOfBoundsException
exceptions probably because of the charAt
method but I'm stuck.我得到
IndexOutOfBoundsException
异常可能是因为charAt
方法,但我被卡住了。 I know I have to use isUpperCase
but I'm not sure exactly where.我知道我必须使用
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
}
You must have a breaking condition in recursion to finally come out.您必须在递归中具有破坏条件才能最终出来。 That condition is missing in your code and you are getting the exception when length of your string is 1.
您的代码中缺少该条件,并且当您的字符串长度为 1 时,您会收到异常。
Try checking String's length before calling isUpperCase.在调用 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;
}
}
try like this, does exactly what you need像这样尝试,正是您所需要的
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.