字符串索引超出范围

时间:2011-02-16 02:20:10

标签: java

我试图让这个程序计算连续字符的数量 并且我得到的错误是:“字符串索引超出范围。”谁能帮我 解决这个问题?

import javax.swing.*;

public class Project0 {
    public static void main(String[] args){

        String sentence;
        sentence = JOptionPane.showInputDialog(null, "Enter a sentence:"); /*Asks the user to
                                                                             enter a sentence*/
        int pairs = 0;
        for (int i = 0; i < sentence.length(); i++){     //counts the pairs of consecutive characters
            if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
        }

        JOptionPane.showMessageDialog(null, "There were " + pairs + " pairs of consecutive characters");
    }//main
}// Project0

3 个答案:

答案 0 :(得分:2)

循环中的最后一个元素100%保证会导致问题。也许只有你的循环中的长度为1?

考虑代码:

for (int i = 0; i < sentence.length(); i++){
    if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
}

String s = "AABBCC";

first loop, i = 0 : compare s[0] to s[1]
first loop, i = 1 : compare s[1] to s[2]
first loop, i = 2 : compare s[2] to s[3]
first loop, i = 3 : compare s[3] to s[4]
first loop, i = 4 : compare s[4] to s[5]
first loop, i = 5 : compare s[5] to s[6] // WOAH, you can't do that! there is no s[6]!!

答案 1 :(得分:0)

sentence.charAt(i+1)会在for-loop的最后一步导致i + 1 > sentence.length()

答案 2 :(得分:0)

您需要将for循环的上限更改为不会一直到最后,因为查找连续字符的方式是“查看i字符,然后看下一个 一旦你到达终点, 没有“下一个”,所以只需停在最后一个。

for (int i = 0; i < sentence.length()-1; i++)