AAV
AAV

Reputation: 433

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

Upvotes: 2

Views: 3848

Answers (3)

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56418

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

Upvotes: 0

Aleksi Yrttiaho
Aleksi Yrttiaho

Reputation: 8456

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

Upvotes: 0

corsiKa
corsiKa

Reputation: 82599

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

Upvotes: 3

Related Questions