ENUM
c++ enum;
c++ 中的枚举内容,是可以直接映射为0, 1, 2, ...等
而JAVA中的枚举是一个类,而且还是final类,不可被继承,
但是既然JAVA中的枚举是一个类,那它就具备类该有的东西,
比如:
1. 可以在其中设置构造器
2. 可以在里面定义它的函数
如果想通过键盘输入的内容通过枚举enum,与switch结合,需要在枚举类中自己定义一些些东西
上代码:
package yubo.example.learnabstract;
import java.util.Scanner;
public class SwitchDemo {
public static Scanner scanner = new Scanner(System.in);
public static enum comType{
ADD("add",1),
SUB("sub",2),
MUT("mut",3),
DIV("div",4);
private String _name;
private int _id;
comType(String name, int id) {
_name = name;
_id = id;
}
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
//定义一个静态方法 多例模型
public static comType getType(int num){
switch (num){
case 1:
return comType.ADD;
case 2:
return comType.SUB;
case 3:
return comType.MUT;
case 4:
return comType.DIV;
default:
System.out.println("您没有输入正确的类型,默认计算加法");
return comType.ADD;
}
}
}
public static double computer(){
System.out.println("请输入\t数字1\t数字2\t类别");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int type = scanner.nextInt();
double res = 0;
comType comtype = comType.getType(type); //根据输入的数据获取enum中的值
switch (comtype){
case ADD:
res = num1 + num2;
break;
case SUB:
res = num1 - num2;
break;
case MUT:
res = num1 * num2;
break;
case DIV:
res = num1 * 1.0 / num2;
break;
}
System.out.println(comtype.get_name() + "结果为 " + res );
return res;
}
public static void main(String[] args) {
computer();
}
}
不知道大家敢不敢觉,这样子有点脱裤子放屁多此一举,我为什么要通过枚举,在进行switch,
为什么不直接switch,这样还能少写两行代码。
关于这个问题,我有点想法能说服50%的我,另外50%还说服不了,,如果有大佬能不吝赐教,小弟在此谢过