How do I check if a char is a vowel?

前端 未结 8 1021
醉酒成梦
醉酒成梦 2020-11-30 13:54

This Java code is giving me trouble:

    String word = 
    int y = 3;
    char z;
    do {
        z = word.charAt(y);
         if (z!=         


        
相关标签:
8条回答
  • 2020-11-30 14:30

    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
    
    0 讨论(0)
  • 2020-11-30 14:31

    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.

    0 讨论(0)
提交回复
热议问题