Count the words with vowels

0

This is a function to count the words that start with a vowel and end with this same vowel, but I only get an error.

this is the function

public int vocal2 (Frase f) {
    StringTokenizer tk = new StringTokenizer (f.getOracion());
    int i=0;

    while (tk.hasMoreTokens()) {
        char inicial = tk.nextToken().charAt(0);
        int fil = (tk.nextToken().length()-1);
        char cfinal = tk.nextToken().charAt(fil);
        if (inicial == 'a' || inicial == 'e' || inicial == 'i' || inicial == 'o' || inicial == 'u') {
            if (inicial == cfinal) {
                i++;
            }
        }

    }

    return i;
}

    
asked by Star Hikari 05.11.2018 в 09:34
source

1 answer

1

The problem seems to be that you repeatedly call tk.nextToken() , and each time you move to the next token, which can result in index errors in the location of the characters and fails to scroll through the words. If you save the word or token in an intermediate variable it works without problems. I'll give you an example.

StringTokenizer tk = new StringTokenizer("la casa azul del este");
        int i=0;

    while (tk.hasMoreTokens()) {
        String word = tk.nextToken();
        char inicial = word.charAt(0);
        //System.out.println(inicial);
        int fil = (word.length()-1);
        char cfinal = word.charAt(fil);
        //System.out.println(cfinal);
        if (inicial == 'a' || inicial == 'e' || inicial == 'i' || inicial == 'o' || inicial == 'u') {
            if (inicial == cfinal) {
              i++;
            }
        }

    }

    System.out.println(i); //imprime 1
    
answered by 05.11.2018 в 11:00