Ekaterina1234
Ekaterina1234

Reputation: 410

java.lang.StringIndexOutOfBoundsException: String index out of range:

I know that simillar questions have been asked, but they all had the same problem: inside of the loop they had something like

i <= aString.lenth()

I used

i < phrase.length();

and I'm still getting the error. I also tried

i < phrase.length()-1;

Any ideas what is wrong?

Thanks.

public class WordPlay {
    public boolean isVowel(char c) {
        if(c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' ||     c=='u' || c=='U') {    
            return true;
        }    
        else
        {
            return false;
        }    
    }
    public void testIsVowel () {
        System.out.println(isVowel('F'));
    }
    public String replaceVowels (String phrase, char ch){
        StringBuilder replaced = new StringBuilder(phrase);
        for (int i = 0; i<phrase.length(); i++) {
            char currChar = phrase.charAt(i);
            if (isVowel(currChar)){

                    //the line below causes the error
                    replaced.setCharAt(currChar, ch);
            }    
        }    
        return replaced.toString();    
    }
    public void testReplaceVowels() {
        System.out.println(replaceVowels("Hello World", '*'));

    }    
}

Upvotes: 1

Views: 5943

Answers (2)

Necromancer
Necromancer

Reputation: 929

The following code is the setCharAt method of AbstractStringBuilder class.

public void setCharAt(int index, char ch) {
    if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    value[index] = ch;
}

If you are passing character 'a' to setCharAt method, it will be implicitly cast from character to int value 97 at index . It made java.lang.StringIndexOutOfBoundsException. Thanks :)

Upvotes: 2

Eran
Eran

Reputation: 394136

In your call to StringBuilder.setCharAt

replaced.setCharAt(currChar, ch);

the first argument should be i, not currChar:

replaced.setCharAt(i, ch);

You should pass the index you want to set the char at, not the character itself.

currChar's int value is probably higher than the length of your StringBuilder, which caused the exception, but if it wasn't, you would get strange output without an exception, which is even worse.

Upvotes: 6

Related Questions