java - 如何检查Java句子中有多少个辅音和元音?

时间:2023-04-06
本文介绍了java - 如何检查Java句子中有多少个辅音和元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在循环结束时,我计划显示句子中辅音和元音的数量.我想知道是否有一种更有效的方法来检查给定句子中有多少个辅音和元音,而不是使用 if 语句并手动输入每个字母.(key指的是我的Scanner,已经初始化)

At the end of my loop, I am planning on displaying the number of consonants and vowels in the sentence. I was wondering if there was a more efficient way to check how many consonants and vowels are in a given sentence, rather than using an if statement and manually inputting every letter. (key refers to my Scanner which has already been initialized)

它需要忽略数字和其他特殊字符,例如,如果我写 Hello@ how 1are you?.应该有8个元音和6个辅音.

It needs to ignore digits and other special characters, so for example if I write Hello@ how 1are you?. There should be 8 vowels and 6 consonants.

System.out.println("Please enter the sentence to analyze: ");

String words = key.nextLine(); //the sentence the user inputs
int c = 0; //# of consonants
int v = 0; //# of vowels
int length = words.length(); //length of sentence
int check; //goes over each letter in our sentence

for(check = 0; check < length; check++){
char a = words.charAt(check);   

        if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
            || a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
            v = v + 1;
        else if(a == 'b' || a == 'B' || a == 'c' || a == 'C' || a == 'd' || a == 'D' || a == 'f'
            || a == 'F' || a == 'g' || a == 'G' || a == 'h' || a == 'H' || a == 'j' || a == 'J' 
            || a == 'k' || a == 'K' || a == 'l' || a == 'L' || a == 'm' || a == 'M' || a == 'n' 
            || a == 'N' || a == 'p' || a == 'P' || a == 'q' || a == 'Q' || a == 'r' || a == 'r'
            || a == 's' || a == 'S' || a == 't' || a == 'T' || a == 'v' || a == 'V' || a == 'w'
            || a == 'W' || a == 'x' || a == 'X' || a == 'z' || a == 'Z')
                c = c + 1;
}

推荐答案

使用Character.isLetter(ch)判断字符是元音还是辅音,然后检查字符是否有问题的是元音组.

Use Character.isLetter(ch) to determine if the character is a vowel or a consonant, then check to see if the character in question is in the set of vowels.

创建元音集的一种方法:

One way to create the set of vowels:

    Set<Character> vowels = new HashSet<Character>();
    for (char ch : "aeiou".toCharArray()) {
        vowels.add(ch);
    }

并增加 vc:

    if (Character.isLetter(a)) {
        if (vowels.contains(Character.toLowerCase(a))) {
            v++;
        } else {
            c++;
        }
    }

这篇关于java - 如何检查Java句子中有多少个辅音和元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Java - 将小写转换为大写而不使用 toUppercase() 下一篇:比较时忽略char上的大写和小写

相关文章