Joseph Goliber Joseph Goliber - 1 month ago 9
Java Question

Sorting Strings in an ArrayList by amount of vowels

For class, I need to perform a multi-way sort on a text file. Specifically, I need to organize the words by vowel count, and then by length. My issue lies with sorting the Array by amount of vowels.

What I'm attempting to do is iterate over every word and count the vowels for that word. Depending on the amount of vowels, it gets added to a corresponding queue.

private static void vowelQueues(String[] words) {

Queue<String> noVowel = new LinkedList<String>();
Queue<String> oneVowel = new LinkedList<String>();
Queue<String> twoVowel = new LinkedList<String>();
Queue<String> threeVowel = new LinkedList<String>();
Queue<String> fourVowel = new LinkedList<String>();
Queue<String> fiveVowel = new LinkedList<String>();
Queue<String> sixVowel = new LinkedList<String>();
Queue<String> sevenVowel = new LinkedList<String>();
Queue<String> eightVowel = new LinkedList<String>();
Queue<String> nineVowel = new LinkedList<String>();
Queue<String> tenVowel = new LinkedList<String>();

char ch;
String vowelHolder = "";
int numVowels = 0;
for (String word : words) {


for (int i = 0; i < word.length(); i++) {
ch = word.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
numVowels++;
if (numVowels == 1) {
oneVowel.add(word);
numVowels = 0;
} else if (numVowels == 2) {
twoVowel.add(word);
numVowels=0;
} else if (numVowels == 3) {
threeVowel.add(word);
numVowels=0;
}
}
}
}


System.out.print(oneVowel); //These are test output statements
System.out.print(twoVowel);
System.out.println(threeVowel);

}


The issue is that all the words containing a vowel gets added to the oneVowel queue and the rest remain empty. I think it's because as soon as numVowels gets incremented once the first if statement adds the whole word to the first queue.

How would I make it so it counts all the vowels in a word and then adds it to it's respective queue?

Answer

This is happening because you are assigning zero to the variable numVowels when any of the condition is true. Your numVowels variable never gets incremented and always the first condition becomes true. So, only elements are added in the oneVowel queue.

for (String word : words) {
     numVowels = 0;
     for (int i = 0; i < word.length(); i++) {
          ch = word.charAt(i);
          if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
              numVowels++;
          }
     }
     if (numVowels == 1) {
         oneVowel.add(word);
     } else if (numVowels == 2) {
         twoVowel.add(word);
     } else if (numVowels == 3) {
         threeVowel.add(word); 
     }
}
Comments