JAVA-ENUM枚举-复习补漏与swtich结合

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%还说服不了,,如果有大佬能不吝赐教,小弟在此谢过
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值