switch语句允许针对值列表对变量进行相等性测试。每个值称为一个案例,并针对每种情况检查要打开的变量。要验证给定字符是否为元音,请将用户的字符读入变量(例如ch)。
定义布尔布尔变量,并将其初始化为false。
使用大写和小写的元音字符('a','e','i','o','u')定义字符ch的大小写,而无需使用break语句。
对于所有这些分配,使bool变量为true。
最后,如果bool变量的值为true,则给定字符为元音,否则为辅音
import java.util.Scanner;
public class VowelOrConsonantSwitch {
public static void main(String args[]) {
boolean bool = false;
System.out.println("输入字符:");
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
switch(ch) {
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' :
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' : bool = true;
}
if(bool == true){
System.out.println("Given character is an vowel ");
}else{
System.out.println("Given character is a consonant ");
}
}
}输出结果
输入字符: a Given character is an vowel 输入字符: l Given character is a consonant