Home > database >  Add words to StringBuffer
Add words to StringBuffer

Time:10-29

in my problem I have to check if a word has a vowel at the beginning of the word and then at the end of the word and if it meets the condition I have to add it in a StringBuffer, I tried but it's not correct, I get some errors and I don't figure out why. Any help, thank you

class MasinaDeTeme {
    private static StringBuffer sb = new StringBuffer();

    public static boolean isVowel(String c) {
        return "AEIOUaeiou".indexOf(String.valueOf(c)) != -1;
    }

    public static StringBuffer filtrareCuvinte(String[] cuvinte) {
        for (int i = 1; i <= cuvinte.length;  i){
            if (isVowel(cuvinte[i]) && isVowel(cuvinte[cuvinte.length])){
                sb.append(cuvinte);
            }
        }
        return sb;
    }
}
class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(MasinaDeTeme.filtrareCuvinte(new String[]{"ana","are","mere"}).toString()); // anaare;
    }
}

CodePudding user response:

public static void main(String... args) {
    StringBuilder buf = filtrareCuvinte(new String[] { "ana", "are", "mere" });
    System.out.println(buf);
}

public static StringBuilder filtrareCuvinte(String[] words) {
    StringBuilder buf = new StringBuilder();

    for (String word : words)
        if (isVowel(word.charAt(0)) && isVowel(word.charAt(word.length() - 1)))
            buf.append(word);

    return buf;
}

private static boolean isVowel(char ch) {
    ch = Character.toLowerCase(ch);
    return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

CodePudding user response:

This seems to be the solution you are looking for. As noted in the comments, you don't need to compare the boolean result of isVowel to another boolean. Also, you should be checking the first and last characters of each string in the String[] to see if they are vowels.

The function filtrareCuvinte can be broken down into two parts.

  1. Iterate each element of the String[]. Example: for (String str : cuvinte)
  2. Check to see if both the first and last characters of the current string are vowels. Example: isVowel(str.charAt(0)) && isVowel(str.charAt(str.length() - 1))

class MasinaDeTeme {
    private static StringBuffer sb = new StringBuffer();

    public static boolean isVowel(char c) {
        return "AEIOUaeiou".indexOf(String.valueOf(c)) != -1;
    }

    public static StringBuffer filtrareCuvinte(String[] cuvinte) {

        for (String str : cuvinte) {
            if (isVowel(str.charAt(0)) && isVowel(str.charAt(str.length() - 1))){
                sb.append(str);
            }
        }

        return sb;
    }
}
class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(MasinaDeTeme.filtrareCuvinte(new String[]{"ana","are","mere"}).toString()); // anaare;
    }
}
  •  Tags:  
  • java
  • Related