JAVA 枚举的简单应用


public class Test {
public static void main(String[] args) {
for (Education e : Education.values()) {
System.out.println("Name : " + e.getName() + " | Value : "
+ e.getValue());
}
System.out.println(Education.Shuoshi.getName());
System.out.println(Education.Benke.getValue());
System.out.println("=================================================");
double x = 5;
double y = 10;
for (Operation op : Operation.values()) {
System.out.println(x + op.toString() + y + " = " + op.apply(x, y));
}
}
}

enum Education {
Boshi("博士", 1), Shuoshi("硕士", 2), Benke("本科", 3), Gaozhong("高中", 4);
private String name;
private int value;

private Education(String name, int value) {
this.name = name;
this.value = value;
}

public String getName() {
return this.name;
}

public int getValue() {
return this.value;
}
}

enum Operation {
PLUS("+") {
@Override
double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
double apply(double x, double y) {
return x - y;
}
},
TIMES("*") {
@Override
double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
@Override
double apply(double x, double y) {
return x / y;
}
};
private String symbol;

private Operation(String symbol) {
this.symbol = symbol;
}

abstract double apply(double x, double y);

@Override
public String toString() {
return this.symbol;
}
}

输出结果:
Name : 博士 | Value : 1
Name : 硕士 | Value : 2
Name : 本科 | Value : 3
Name : 高中 | Value : 4
硕士
3
=================================================
5.0+10.0 = 15.0
5.0-10.0 = -5.0
5.0*10.0 = 50.0
5.0/10.0 = 0.5

[b]利用枚举实现java单例:包含一个元素的枚举:[/b]

enum Singleton{
INSTANCE;
public void doSomething(){
//...
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值