Home > Net >  How to concatenate words that starts and end with a vowel?
How to concatenate words that starts and end with a vowel?

Time:05-07

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?

CodePudding user response:

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;
}

CodePudding user response:

Try this:

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;
    }

CodePudding user response:

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]);

CodePudding user response:

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;
}
  •  Tags:  
  • java
  • Related