错误越界说,
java.lang.StringIndexOutOfBoundsException:超出范围的字符串索引: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;
}发布于 2018-10-01 19:35:44
这里有3个问题:
1)将<= bcount改为< bcount。
2)在第二个for循环中,您正在执行i++,但它应该是l++
3)第一个for循环中的条件应该是i < acount,而不是i<bcount
发布于 2018-10-01 19:36:16
在大多数语言中,像大多数语言一样,字符串的索引以0开头,因此,字符串的最后一个索引实际上是str.length() - 1。
使用<=进行测试时,变量会增加,直到值等于长度为止,这是一个超出绑定的索引。
而是使用<对两种测试进行测试。变量将在该字符串的最后一个字符之后停止,而不是使用不存在的索引进行最后一次尝试。
发布于 2018-10-01 20:00:59
当您运行此代码时,它将返回3,不确定这是否符合您对返回值的期望。你必须改变一些事情
for(int i = 0; i < acount; i++)for(int l = 0; i < bcount; l++)
公共静态空(String[] args){ System.out.println( countAlike (“高兴”,“潮湿”));}公共静态int countAlike(字符串a,字符串b){ int acount = a.length();int bcount = b.length();int countAlike= 0;for(int i= 0;i< acount;i++){ for(int l= 0;l如果在for循环中的If语句中有System.out.println(a.substring(i, i+1));和System.out.println(b.substring(l, l+1));,则If将打印出a a p p p p。
https://stackoverflow.com/questions/52597700
复制相似问题