当前位置:网站首页>if/else或switch替换为Enum
if/else或switch替换为Enum
2022-08-03 18:54:00 【帅宇Yeah~】
if/else或switch替换为Enum
if else 使用
/**
* 调用
* @param args
*/
public static void main(String[] args) {
int type = 8;
eatFood(type);
}
/**
* 使用if判断
* @param type
*/
public static void eatFood(int type){
if(1 == type){
System.out.println("火锅");
} else if (2 == type) {
System.out.println("烤肉");
} else if (3 == type) {
System.out.println("烤鱼");
}else{
System.out.println("饿着");
}
}
switch 使用
/**
* 调用
* @param args
*/
public static void main(String[] args) {
int type = 8;
eatFood(type);
}
/**
* 使用switch判断
* @param type
*/
public static void eatFood(int type){
switch (type){
case 1:
System.out.println("火锅");
break;
case 2:
System.out.println("烤肉");
break;
case 3:
System.out.println("烤鱼");
break;
default:
System.out.println("饿着");
break;
}
}
================================================
Enum
import java.util.HashMap;
import java.util.Map;
public class TestClass {
private final static Map<Integer, String> map;
static {
map = new HashMap<>();
map.put(1, "TYPE_1");
map.put(2, "TYPE_2");
map.put(3, "TYPE_3");
}
/**
* 调用
* @param args
*/
public static void main(String[] args) {
//map种不存在的key默认为TYPE_4
String type = map.getOrDefault(8,"TYPE_4");
EatEnum.valueOf(type).eatFood();
}
}
/**
* 接口
*/
public interface EatFood {
void eatFood();
}
/**
* 枚举类实现EatFood接口
*/
public enum EatEnum implements EatFood{
TYPE_1(){
@Override
public void eatFood() {
System.out.println("火锅");
}
},
TYPE_2(){
@Override
public void eatFood() {
System.out.println("烤肉");
}
},
TYPE_3(){
@Override
public void eatFood() {
System.out.println("烤鱼");
}
},
TYPE_4(){
@Override
public void eatFood() {
System.out.println("饿着");
}
};
}
边栏推荐
猜你喜欢
字节跳动三面拿offer:网络+IO+redis+JVM+GC+红黑树+数据结构,助你快速进大厂!!
mysql跨库关联查询(dblink)
高数---级数
Cobalt Strike (CS) 逆向初探
细胞不可渗透的荧光探针 锌离子荧光探针Zinquin 151606-29-0
Alibaba senior experts create a learning architecture from scratch, including Alibaba's internal technology stack PPT, PFD actual combat
选出表中的中位数记录[构造左右边界 || 问题转换]
OneNote 教程,如何在 OneNote 中设置页面格式?
B628芯片电路图,B628升压IC的PCB布局PCB
MySQL如何 drop 大表
随机推荐
在线监控机房内的UPS电源及运行环境,解决方案来了
201712-3 CCF Crontab满分题解
Blender script 删除所有幽灵对象
[笔记]机器学习之前言介绍
B628芯片电路图,B628升压IC的PCB布局PCB
MySQL【变量、流程控制与游标】
[数据集][VOC]老鼠数据集voc格式3001张
VsCode预览Geojson数据
Shell编程案例
APT级全面免杀与企业纵深防御体系的红蓝对抗
2022年7月国产数据库大事记
盲僧发现了华点——教你如何使用API接口获取数据
openresty 高可用部署
系统太多,多账号互通如何实现?
细胞不可渗透的荧光探针 锌离子荧光探针Zinquin 151606-29-0
87. (Home of cesium) cesium heat map (topography)
PHP Basic Notes-NO.2
idea——同一项目开启多个实例(不同端口)
Zhong Hua, senior architect of Ali: China-Taiwan strategic thinking and architecture practice; including internal implementation manual
2022/08/02------丑数