思路:以某一个单位为基准创建一个枚举类import java.math.BigDecimal;
import java.util.Optional;
public enum LengthUnitEnum {
/**
* 公里 以 1公里未标准
*/
KILOMETRE((byte) 1, new BigDecimal(“1”)),
/**
* 米
*/
METER((byte) 2, new BigDecimal(“1000”)),
/**
* 分米
*/
DECIMETER((byte) 3, new BigDecimal(“10000”)),
/**
* 厘米
*/
CENTIMETER((byte) 4, new BigDecimal(“100000”)),
/**
* 毫米
*/
MILLIMETER((byte) 5, new BigDecimal(“1000000”)),
/**
* 微米
*/
MICROMETER((byte) 6, new BigDecimal(“1000000000”)),
/**
* 里
*/
LI((byte) 7, new BigDecimal(“2”)),
/**
* 丈
*/
ZHANG((byte) 8, new BigDecimal(“300”)),
/**
* 尺
*/
RULER((byte) 9, new BigDecimal(“3000”)),
/**
* 寸
*/
SMALL((byte) 10, new BigDecimal(“30000”)),
/**
* 分
*/
MINUTE((byte) 11, new BigDecimal(“300000”)),
/**
* 厘
*/
CENTI((byte) 12, new BigDecimal(“3000000”)),
/**
* 海里
*/
SEA_MILE((byte) 13, new BigDecimal(“0.5399568”)),
/**
* 英寻
*/
FATHOM((byte) 14, new BigDecimal(“546.8066492”)),
/**
* 英里
*/
MILE((byte) 15, new BigDecimal(“0.6213712”)),
/**
* 弗隆
*/
FURLONG((byte) 16, new BigDecimal(“4.9709695”)),
/**
* 码
*/
CODE((byte) 17, new BigDecimal(“1093.6132983”)),
/**
* 英尺
*/
FOOT((byte) 18, new BigDecimal(“3280.839895”)),
/**
* 英寸
*/
INCH((byte) 19, new BigDecimal(“39370.0787402”));
private byte id;
private BigDecimal value;
LengthUnitEnum(byte id, BigDecimal value) {
this.id = id;
this.value = value;
}
public byte getId() {
return id;
}
public BigDecimal getValue() {
return value;
}
public static Optionalget(Byte id) {
Optionalrtn = Optional.empty();
if (id != null) {
for (LengthUnitEnum code : values()) {
if (code.getId() == id) {
rtn = Optional.of(code);
}
}
}
return rtn;
}
}
实现起来也很简单@Override
public ListconverterLengthUnit(ConverterLengthUnitQuery query) throws ServiceException {
Listrtn = new ArrayList();
ConverterLengthUnitDTO converterLengthUnitDTO;
LengthUnitEnum unitEnum = LengthUnitEnum.get(query.getUnit()).orElseThrow(() -> new ServiceException(“单位错误”, ProjectResultCodeEnum.FAIL.getCode()));
//都先转换为千米
BigDecimal kilometre = query.getNumber().divide(unitEnum.getValue());
for (LengthUnitEnum lengthUnitEnum : LengthUnitEnum.values()) {
converterLengthUnitDTO = new ConverterLengthUnitDTO();
converterLengthUnitDTO.setUnit(lengthUnitEnum.getId())
.setValue(lengthUnitEnum.getValue().multiply(kilometre));
rtn.add(converterLengthUnitDTO);
}
return rtn;
}
文章知识点与官方知识档案匹配,可进一步学习相关知识Java技能树首页概览93627 人正在系统学习中 相关资源:各种单位换算器软件(长度、面积、体积等)_c语言分米和厘米转换…
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!