Converting different unit types in JScience library

孤人 提交于 2019-12-02 04:13:24

It looks like JScience has caught you trying to convert a Unit<Mass> to a Unit<Energy>, which is forbidden in the default PhysicalModel.

One alternative approach would be to create a new Quantity for various units of FoodEnergy:

public static final Unit<Energy> KILOCALORIE = SI.JOULE.times(4184);

public interface FoodEnergy extends Quantity {

    public final static Unit<FoodEnergy> UNIT
        = (Unit<FoodEnergy>) SI.GRAM.times(KILOCALORIE);
}

private static final Unit<FoodEnergy> PROTEIN_ENERGY = FoodEnergy.UNIT.times(4);
private static final Unit<FoodEnergy> ETHANOL_ENERGY = FoodEnergy.UNIT.times(7);
…

You can then combine the contributions of particular energy sources:

Amount<FoodEnergy> beer =
    Amount.valueOf(2, PROTEIN_ENERGY).plus(
    Amount.valueOf(14, ETHANOL_ENERGY));
System.out.println(beer.to(FoodEnergy.UNIT).getEstimatedValue() + " Calories");

Which prints 105.99999999999997 Calories. You can find the calories in a pound of protein by converting a NonSI.POUND to SI.GRAM:

double grams = NonSI.POUND.getConverterTo(SI.GRAM).convert(1);
Amount<FoodEnergy> pound = Amount.valueOf(grams, PROTEIN_ENERGY);
System.out.println(pound.to(FoodEnergy.UNIT).getEstimatedValue() + " Calories");

Which prints 1814.3694799999998 Calories. Finally, you can recover the number of Joules from a FoodEnergy.UNIT:

System.out.println(FoodEnergy.UNIT.divide(SI.GRAM));

Which prints J*4184, or

System.out.println(FoodEnergy.UNIT.divide(SI.GRAM).toStandardUnit().convert(1));

Which prints 4184.0.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!