Skip to content
Advertisement

Java Vowel count using Collection

I am asked to write a code to count and display vowels in a String using Sets. Any suggestions as to why the code below gives wrong output? Switch seemed like the obvious approach, I also tried with an if-statemen, but neither work properly.

import java.util.*;

class Vowels {
String s;   
Set<String> set = new HashSet<String>();
Vowels(String s, LinkedHashSet<String> set) {
    this.s = s;
    this.set = set;
}
public void evaluator() {  
    Collections.addAll(set, s.split(""));
    int vn = 0;
    String vowel = "";
    List<String> vowels = new ArrayList<String>();
    Iterator<String> it = set.iterator();
    while(it.hasNext()) {
        switch(it.next()) {
        case "a":
        case "e":
        case "i":
        case "o":
        case "u":
        case "y":
        case "w": 
            vn++;       
            vowel = it.next();
            vowels.add(vowel);  
        }
    }
    System.out.println("Number of vowels is " + vn);
    System.out.println("Vowels are " + vowels);
}
}

public class ExXVI {
public static void main(String[] args) {
    LinkedHashSet<String> set1 = new LinkedHashSet<String>();
    Vowels q = new Vowels("Some words have vowels, some do not", set1);
    q.evaluator();
}
} /* Output:
Number of vowels is 4
Vowels are [m,  , r, v]
*///:~

Advertisement

Answer

I’m pretty sure it’s partially because you’re counting ‘Y’ and ‘W’ as vowels. Also, when you go to save the vowel, you call it.next() again. This actually gets the next object in the collection, not the one you just compared in the switch. You should save the value of it.next() before the switch, then use the variable to reference it later.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement