java字符串索引超出绑定异常,字符串索引超出范围
所以,我写了一个简单的程序来输入一个字符串,然后计算m的总数。 这是我的代码
for(int i=0; i<=n; i++)
{
if((str.charAt(i)=='m'))
{
} else {
count++;
}
}
System.out.println("The total number of m is "+count);
其中n=str.length();
str是我取的一个字符串,但是这个错误不断出现
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14
at java.lang.String.charAt(String.java:646)
at javaapplication.JavaApplication.main(JavaApplication.java:28
Java Result: 1
这个错误是什么?如何删除它
# 1 楼答案
假设您有以下长度为7的数组:
在这种情况下,
for(int i=0; i<=n; i++)
的for循环将循环8次,从索引0到7进行迭代但是索引7处的数组元素不存在,因此给出
outOfBoundsException
其中作为
for(int i=0; i<n; i++)
的for循环将循环7次,从0迭代到6次