我似乎无法找到/记住将体积单位转换为质量单位的特定公式。我认为这与密度有关,但如何做到这一点?
就我而言,我正在尝试使用JScience 库编写一个程序,以将用户可能输入的任何类型的单位转换为标准SI.GRAM
单位。
问题在于试图描述蜂蜜之类的东西,通常以加仑、克、磅和盎司为单位。
我有以下代码主要在使用质量单位时工作,但ConversionException
在尝试使用加仑时我得到一个,这是可以理解的,因为它测量的是体积而不是质量。
javax.measure.converter.ConversionException: gal is not compatible with g
这是我到目前为止所得到的。另外,我选择将其分解Amount<Mass>
为amount_value
,amount_unit
因为我想将其存储在 SQLite 数据库中,并将其表示为文本,因此出于序列化目的,我将其存储为这样。
public class Sugar {
private String type;
private double amount_value;
private String amount_unit;
public Sugar(SUGAR_TYPES type, Amount<Mass> amount) {
this.type = type.toString();
this.amount_value = amount.getEstimatedValue();
this.amount_unit = amount.getUnit().toString();
}
public Amount<Mass> getAmount() {
BaseUnit<Mass> mass_unit = new BaseUnit<>(amount_unit);
return Amount.valueOf(amount_value, mass_unit);
}
public SUGAR_TYPES getType() {
return (type != null) ? SUGAR_TYPES.valueOf(type) : null;
}
public double getAmountInGrams() {
Amount<Mass> mass_unit = getAmount();
switch (mass_unit.getUnit().toString().toLowerCase()) {
case "g":
return mass_unit.getEstimatedValue();
case "gal":
// this throws the ConversionException
return NonSI.GALLON_LIQUID_US.getConverterTo(SI.GRAM).convert(mass_unit.getEstimatedValue());
case "lb":
return NonSI.POUND.getConverterTo(SI.GRAM).convert(mass_unit.getEstimatedValue());
default:
Log.e(TAG, String.format("Failed to get Amount<Mass> in SI.GRAM for amount %s and unit %s.",
amount_value, amount_unit));
throw new IllegalArgumentException(mass_unit.getUnit().toString());
}
}
public enum SUGAR_TYPES {
HONEY, SUCROSE, APPLES, APRICOTS, APRICOTS_DRIED, BANANAS, BLACKBERRY, BLUEBERRY,
BOYSENBERRY, CANTALOUPE, CELERY, CHERRY_DARK_SWEET, CRANBERRY, CURRANT_BLACK, DATES,
DATES_DRIED, DEWBERRY, ELDERBERRY, FIGS, FIGS_DRIED, GOOSEBERRY, GRAPE_CONCORD,
GRAPES, GRAPEFRUIT, GUANABANA, GUAVAS, HONEYDEW_MELON, JACKFRUIT, KIWIS, LEMON_JUICE,
LITCHI, LOGANBERRY, MANGOS, MAPLE_SYRUP, PLUMS, RAISINS_DRIED, RASPBERRY_BLACK,
RASPBERRY_RED, RHUBARB, STRAWBERRY, TANGERINES, WATERMELONS
}
}
有没有更好的方法来做到这一点?我有其他类需要有类似的方法将通用单位转换为 SI 单位。