string index out of bound 异常,String index out of range

string index out of bound exception, String index out of range

所以,我在写一个简单的程序来输入一个字符串并计算总数。的米。 所以,这是我的代码

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

这是什么错误以及如何删除它?

length() == n 的字符串具有从 0 到 n-1 的有效索引;

改变

for(int i=0; i<=n; i++)

for(int i=0; i<n; i++)

请记住,字符串的索引从 0 到 StringName.length() - 1。由于您正在遍历 StringName().length - 您实际上是在字符串的 "bounds" 之外导致错误。您需要确保您的索引在 for 循环中是正确的。

字符串变量中的字符从 0 索引开始。

此外,如果你想统计小写字母 m 的总出现次数,请将你的 count++ 移动到你的 if block statement.

 n=str.length() - 1;
    for(int i=0; i<=n; i++)
        {
            if((str.charAt(i)=='m'))
            {
                  count++;
            }
        }
        System.out.println("The total number of m is "+count);

假设您有以下 长度为 7 的数组:

-----------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |  <-- Array index
-----------------------------
|10 |20 |30 |40 |50 |60 |70 |  <-- Array values
-----------------------------

在这种情况下,for(int i=0; i<=n; i++) 的 for 循环将循环 8 次,从索引 0 迭代到 7

但是索引 7 处的数组元素不存在,因此给出 outOfBoundsException.

其中 for(int i=0; i<n; i++) 的 for 循环将循环 7 次0 迭代到 6.

charat 与索引一起工作(从到 n-1),但是在你的 for 中你得到了你有 i=n 的条件,在这种情况下 charat 抛出异常,因为它在数组 [= 中没有那个索引10=]