错误超出范围,
java.lang.StringIndexOutOfBoundsException: String index out of range: 6 (in.java.lang.String)
当我运行代码时。我试图找出两个字符串在相同位置有多少个相同的字符。
Public static void main(String[] args) {
System.out.println(countAlike("happy","damp");
}
public static int countAlike(String a, String b) {
int acount = a.length();
int bcount = b.length();
int countAlike = 0;
for(int i = 0; i <= bcount; i++){
for(int l = 0; l <= bcount; i++){
if(a.substring(i,i+1).equals(b.substring(l,l+1))){
countAlike += 1;
}
else{
}
}
}
return countAlike;
}
最佳答案
Java 中字符串字符的索引与大多数语言一样都是从 0 开始的,因此,字符串的最后一个索引实际上是 str.length() - 1
.
当您使用 <=
进行测试时,您的变量会递增,直到该值等于您的长度,这是一个超出范围的索引。
而是使用 <
进行测试对于你的两个测试。您的变量将在该字符串的最后一个字符之后停止,而不是最后一次尝试使用不存在的索引。
关于java.lang.StringIndexOutOfBoundsException : String index out of range: 6 (in. java.lang.String),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52597700/