900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java 单位转换的程序_Java 实现长度单位换算

java 单位转换的程序_Java 实现长度单位换算

时间:2023-04-05 15:19:22

相关推荐

java 单位转换的程序_Java 实现长度单位换算

思路:以某一个单位为基准创建一个枚举类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;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。