原文: https://www.programiz.com/java-programming/examples/vowel-consonant
public class VowelConsonant {
public static void main(String[] args) {
char ch = 'i';
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )
System.out.println(ch + " is vowel");
else
System.out.println(ch + " is consonant");
}
}运行该程序时,输出为:
i is vowel在上述程序中,'i'存储在char变量ch中。 在 Java 中,对字符串使用双引号(" "),对于字符使用单引号(' ')。
现在,要检查ch是否是元音,我们检查ch是否为以下任何一项:('a', 'e', 'i', 'o', 'u')。 使用简单的if..else语句即可完成此操作。
我们还可以使用 Java 中的switch语句检查元音或辅音。
public class VowelConsonant {
public static void main(String[] args) {
char ch = 'z';
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println(ch + " is vowel");
break;
default:
System.out.println(ch + " is consonant");
}
}
}运行该程序时,输出为:
z is consonant在上面的程序中,我们没有使用长if条件,而是将其替换为switch case语句。
如果ch是以下两种情况之一:('a', 'e', 'i', 'o', 'u'),则输出元音。 否则,执行default case并在屏幕上打印辅音。