示例 1: 使用 if..else 语句检查字母是元音还是辅音
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 语句检查元音或辅音。
示例 2: 使用 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 并在屏幕上打印辅音。