有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    假设您有以下长度为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次