'How to concatenate words that starts and end with a vowel? [duplicate]

I receive a list of words and assigns them to write all the words that start and end with a vowel. I need to write a MasinaDeTeme class that contains a public Word filtering method. The method will receive as a parameter a string of String (String []) and will return a StringBuffer that will contain all the words with the required property concatenated in the order in which they appear in the string.

Here is the part of my cod where is my problem:

public static StringBuffer filtrareCuvinte(String[] cuvinte){
   
    for(int i = 0; i < cuvinte.length; i++)

        if(isVowel(cuvinte[i].charAt(0)) && isVowel(cuvinte[i].charAt(cuvinte.length - 1)))
            s.append(cuvinte[i]);

    return s;
}

}

I receive an error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3

I think its because of the length. Any suggestions?



Solution 1:[1]

You must check the character at the last index of the word, but you search for the last index of words array. Try this:

public static StringBuffer filtrareCuvinte(String[] cuvinte){

    for(String word : cuvinte)
    {
        if(isVowel(word.charAt(0)) && 
              isVowel(word.charAt(word.length - 1)))
        s.append(cuvinte[i]);
    }
    return s;
}

Solution 2:[2]

Your second isVovwel condition is breaking at charAt call; Simply change below inside for loop,

 if(isVowel(cuvinte[i].charAt(0)) && isVowel(cuvinte[i].charAt(cuvinte[i].lenght-1)))
                s.append(cuvinte[i]);

Solution 3:[3]

The problem here is that you in your second call are using the length of the String[] that is passed to the filtrareCuvinte method.

Instead use the following:

public static StringBuffer filtrareCuvinte(String[] cuvinte){
    StringBuffer sb = new StringBuffer();
    
    for(int i = 0; i < cuvinte.length; i++){
        if(isVowel(cuvinte[i].charAt(0)) && isVowel(cuvinte[i].charAt(cuvinte[i].length() - 1)))
            sb.append(cuvinte[i] + " ");
    }

    return sb;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Müseyib ?l?kb?r
Solution 2 Ashish Patil
Solution 3