gpt4 book ai didi

java - 使用 Jscience 计算 n 个单位的价格(提供单价和数量)

转载 作者:行者123 更新时间:2023-11-30 03:56:59 27 4
gpt4 key购买 nike

我正在寻找一种更好的方法来使用 Jscience 进行计算,但通用模式很难获得清晰的解决方案。如果定义了单位数量的单价,我需要计算 n 个单位的价格。就像,

    Measure<Double, ? extends Quantity> unitQuantity = Measure.valueOf(1.0,
Unit.valueOf("kg"));
Amount<Money> unitPrice = Amount.valueOf(150.0, USD);
Measure<Double, ? extends Quantity> quantity = Measure.valueOf(500.0,
MILLI(Unit.valueOf("kg")));
Amount<Money> amount = unitPrice.times(quantity.to(unitQuantity.getUnit())
.getValue() / unitQuantity.getValue());

对于上面的代码,我收到此错误:

The method to(Unit<capture#7-of ? extends Quantity>) in the type 
Measure<Double,capture#7-of ? extends Quantity> is not applicable for
the arguments (Unit<capture#8-of ? extends Quantity>)

我在 Java Tutorials 阅读了有关泛型的内容并尝试了以下方法,但仍然没有明确的解决方案:

    Amount<Money> amount = compute(unitPrice,unitQuantity,quantity)

private <T extends Quantity> Amount<Money> compute(Amount<Money> unitPrice,
Measure<Double, T> unitQuantity, Measure<Double, T> quantity) {
return unitPrice.times(quantity.to(unitQuantity.getUnit()).getValue()
/ unitQuantity.getValue());
}

现在收到此错误:

   The method compute(Amount<Money>, Measure<Double,T>, Measure<Double,T>) 
in the type JscienceEx is not applicable for the arguments (Amount<Money>,
Measure<Double,capture#7-of ? extends Quantity>, Measure<Double,capture#8-of ?
extends Quantity>)

最佳答案

Unit.valueOf("kg")工厂方法在某些情况下可能很方便。但在这种情况下,它没有保留足够的信息。它仅返回“某些”数量的单位 - 因此 ? extends Quantity在返回类型中。但你不知道这是否是数量,例如MassPower 。而只要你不知道这一点,你就无法判断是否调用了quantity.to(unitQuantity.getUnit())有效。

在这种情况下,您可以使用 new BaseUnit<Mass>("kg") 来解决此问题而不是 Unit.valueOf("kg") :

import static javax.measure.unit.SI.MILLI;

import javax.measure.Measure;
import javax.measure.quantity.Mass;
import javax.measure.unit.BaseUnit;

import org.jscience.economics.money.Currency;
import org.jscience.economics.money.Money;
import org.jscience.physics.amount.Amount;

public class JScienceUnits
{
public static void main(String[] args)
{
BaseUnit<Mass> kg = new BaseUnit<Mass>("kg");
Measure<Double, Mass> unitQuantity = Measure.valueOf(1.0, kg);
Amount<Money> unitPrice = Amount.valueOf(150.0, Currency.USD);
Measure<Double, Mass> quantity = Measure.valueOf(500.0, MILLI(kg));
Amount<Money> amount = unitPrice.times(
quantity.to(unitQuantity.getUnit()).getValue() /
unitQuantity.getValue());

System.out.println(
"Money for "+quantity+
" with unit price "+unitPrice+
" is "+amount);
}
}

关于java - 使用 Jscience 计算 n 个单位的价格(提供单价和数量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22918549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com