2

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

3 Answers 3

3

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]!!
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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++)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.