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

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)

Edit: 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;

}

解决方案

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 vowels = new HashSet();

for (char ch : "aeiou".toCharArray()) {

vowels.add(ch);

}

And to increment v or c:

if (Character.isLetter(a)) {

if (vowels.contains(Character.toLowerCase(a))) {

v++;

} else {

c++;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值