Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a char is a vowel?

This Java code is giving me trouble:

    String word = <Uses an input>
    int y = 3;
    char z;
    do {
        z = word.charAt(y);
         if (z!='a' || z!='e' || z!='i' || z!='o' || z!='u')) {
            for (int i = 0; i==y; i++) {
                wordT  = wordT + word.charAt(i);
                } break;
         }
    } while(true);

I want to check if the third letter of word is a non-vowel, and if it is I want it to return the non-vowel and any characters preceding it. If it is a vowel, it checks the next letter in the string, if it's also a vowel then it checks the next one until it finds a non-vowel.

Example:

word = Jaemeas then wordT must = Jaem

Example 2:

word=Jaeoimus then wordT must =Jaeoim

The problem is with my if statement, I can't figure out how to make it check all the vowels in that one line.

like image 241
Dinocv Avatar asked Oct 03 '13 13:10

Dinocv


3 Answers

Clean method to check for vowels:

public static boolean isVowel(char c) {
  return "AEIOUaeiou".indexOf(c) != -1;
}
like image 170
Silviu Burcea Avatar answered Sep 30 '22 19:09

Silviu Burcea


Your condition is flawed. Think about the simpler version

z != 'a' || z != 'e'

If z is 'a' then the second half will be true since z is not 'e' (i.e. the whole condition is true), and if z is 'e' then the first half will be true since z is not 'a' (again, whole condition true). Of course, if z is neither 'a' nor 'e' then both parts will be true. In other words, your condition will never be false!

You likely want &&s there instead:

z != 'a' && z != 'e' && ...

Or perhaps:

"aeiou".indexOf(z) < 0
like image 23
arshajii Avatar answered Sep 30 '22 17:09

arshajii


How about an approach using regular expressions? If you use the proper pattern you can get the results from the Matcher object using groups. In the code sample below the call to m.group(1) should return you the string you're looking for as long as there's a pattern match.

String wordT = null;
Pattern patternOne = Pattern.compile("^([\\w]{2}[AEIOUaeiou]*[^AEIOUaeiou]{1}).*");
Matcher m = patternOne.matcher("Jaemeas");
if (m.matches()) {
    wordT = m.group(1);
}

Just a little different approach that accomplishes the same goal.

like image 31
jmtrachy Avatar answered Sep 30 '22 19:09

jmtrachy