开发者

String index out of range in Java

I'm trying to make this program to count the number of consecutive characters and I'm getting the error that says:

"String index out of range."

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


The last element in your loop is 100% guaranteed to cause a problem. Perhaps only go to the length - 1 in your loop?

Consider the code:

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]!!


sentence.charAt(i+1) will cause this as i + 1 > sentence.length() at the last step of the for-loop


You need to change the upper limit of your for loop to not go all the way to the end because the way you look for consecutive characters is "look at the ith character, and then look at the next one". Once you get to the end, there is no "next one", so just stop at the next to last one.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜