switch
自定义:
通过判断一个变量与给出的几个选项进行匹配,判断是否相等
语法:
switch(expression){
case value://value是要判断的内容,
break;//可选,不选,后续分支都会输出,初称为“穿透”
case value://value是要判断的内容,
break;//可选,
default://可选
JDK7后可以判断字符串String类型
例子1:
package struct;
public class SwitchDemo01 {
public static void main(String[] args) {
String grade = "A";
switch (grade){
case "A":
System.out.println("优秀");
break;
case "B":
System.out.println("良好");
break;
case "C":
System.out.println("及格");
break;
case "D":
System.out.println("再接再厉");
break;
case "E":
System.out.println("挂科");
break;
default:
System.out.println("未知等级");
}
}
}
自己举例:
还是吃饭,点菜,返回结果 ,结合Scanner。
package struct;
import java.util.Scanner;
public class SwitchDemo01D {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String foodName = scanner.nextLine();
switch(foodName){
case "宫爆鸡丁":
System.out.println("你点了宫爆鸡丁");
break;
case "番茄炒菜":
System.out.println("你点了番茄炒菜");
break;
case "土豆焖鸡":
System.out.println("你点了土豆焖鸡");
break;
default :
System.out.println("你说啥");
break;
}
scanner.close();
}
}