java - 从速度转换为(速度)^-1
问题描述
使用javax.measure库,我尝试将 km/h 转换为 min/km。
但是 min/km 不是unit-ri提出的单位的一部分。
所以我尝试创建自己的单位:MINUTE_BY_KILOMETERS
import javax.measure.Quantity;
import javax.measure.Unit;
import javax.measure.quantity.Length;
import javax.measure.quantity.Speed;
import tec.units.ri.quantity.Quantities;
import tec.units.ri.unit.MetricPrefix;
import tec.units.ri.unit.Units;
Quantity<Speed> speed = Quantities.getQuantity(10, Units.KILOMETRE_PER_HOUR);
assertEquals("10 km/h", speed.toString());
// Conversion m/s
assertEquals("2.7777800000000004 m/s", speed.to(Units.METRE_PER_SECOND).toString());
// Conversion min/km
Unit<Speed> MINUTE_BY_KILOMETERS = Units.MINUTE.divide(MetricPrefix.KILO(Units.METRE)).asType(Speed.class);
assertEquals("6 min/km", speed.to(MINUTE_BY_KILOMETERS).toString());
但我得到一个例外:
java.lang.ClassCastException: The unit: min/km is not compatible with quantities of type interface javax.measure.quantity.Speed
at tec.units.ri.AbstractUnit.asType(AbstractUnit.java:274)
我想我必须创建自己的类型,但我不知道如何。
有人可以提供一个例子吗?
解决方案
速度定义为距离除以时间,因此您不能创建Speed
“分钟每公里”的单位。但是,您可以创建自己的反向速度测量,这只不过是一个标记界面:
public interface InverseSpeed extends Quantity<InverseSpeed> {}
然后创建这样一个单元:
Unit<InverseSpeed> MINUTE_BY_KILOMETERS =
Units.MINUTE.divide(MetricPrefix.KILO(Units.METRE)).asType(InverseSpeed.class);
推荐阅读
- laravel-5 - Auth::guard('admin')->user() 在 laravel 5.8 中为 NULL
- c - Vulkan vkCreateInstance - 访问冲突写入位置 0x0000000000000000
- python - 使用 venv 和 python 2.x 创建环境
- git - Git:安全回滚到以前的主人
- bash - 在 bash 中,如何将无限输出流重定向到处理的文件?
- intellij-idea - Intellij 为不应输出任何内容的键输出奇怪的字符
- lua - 考虑到 roblox studio 中的碰撞时如何移动对象
- ios - UIView 和 UICollection 的动态约束
- javascript - JS TypeError: texte is null - 如何从不为 null 的 textarea 开始?
- github - githubActions:如何显示测试覆盖率?