假设字母A、E、I、O、U 为元音。编写一个程序,提示用户输入一个字符串,然后显示字符串中元音和辅音的数目。
package pack2;
import java.util.Scanner;
public class CountVowelsAndConsonants {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter a string: ");
String string = input.nextLine();
System.out.println("The number of vowels is "+countVowels(string));
System.out.println("The number of consonants is "+countConsonants(string));
}
}
//计数元音
public static int countVowels(String string) {
int count = 0;
string = string.toLowerCase(); //字符串转化为小写
for (char c : string.toCharArray()) {
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++; //如果字符匹配元音中的任意一个,count++
}
return count;
}
//计数辅音
public static int countConsonants(String string) {
int count = 0;
string = string.toLowerCase();
for (char c : string.toCharArray()) {
if('a' <= c && c <= 'z')
if(c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u')
count++; //如果字符为字母且不匹配元音中的任意一个,count++
}
return count;
}
}