在循环结束时,我计划显示句子中辅音和元音的数量。我想知道是否有一种更有效的方法来检查给定句子中有多少个辅音和元音,而不是使用 if 语句并手动输入每个字母。(key指的是我已经初始化的扫描仪)
编辑:它需要忽略数字和其他特殊字符,例如,如果我写 Hello@ how 1are you?。应该有8个元音和6个辅音。
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
用于Character.isLetter(ch)确定字符是元音还是辅音,然后检查相关字符是否在元音集中。
创建元音集的一种方法:
Set<Character> vowels = new HashSet<Character>();
for (char ch : "aeiou".toCharArray()) {
vowels.add(ch);
}
Run Code Online (Sandbox Code Playgroud)
并增加v或c:
if (Character.isLetter(a)) {
if (vowels.contains(Character.toLowerCase(a))) {
v++;
} else {
c++;
}
}
Run Code Online (Sandbox Code Playgroud)