gpt4 book ai didi

java - 将 Double 与方法中计算出的 Double 值相等会导致 0.0?可能是什么问题呢?

转载 作者:行者123 更新时间:2023-11-30 10:06:08 25 4
gpt4 key购买 nike

对于这些表达式:

     if (lim != null) {


for (int i = 0; i < itemlist.size(); i++) {

Double itemquantity = calculateQuantity(itemlist.get(i));

Integer limitvalue = lim.getValue();

System.out.println("CALCULATED VALUE IS: " + calculateQuantity(itemlist.get(i)));

System.out.println("ITEMQUANTITY IS " + itemquantity);

System.out.println("LIMIT VALUE IS " + limitvalue);

if (itemquantity < limitvalue) {
System.out.println("QUANTITY " + itemquantity + " vs LIMIT " + limitvalue);
below.add(itemlist.get(i).getName());
}}

我得到以下结果:

CALCULATED VALUE IS: **210.0** 
ITEMQUANTITY IS **0.0**
LIMIT VALUE IS **500**
QUANTITY 0.0 vs LIMIT 500

这是返回 Double 的 calculateQuantity() 方法,但该方法的工作原理与输出所示相同:

     public Double calculateQuantity(Items item)
{
Double quantity = 0.0;
int ID = item.getItemId();
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();

Query query = session.createQuery("select sum(t.flow * a.inOrOut) from Advicenote a join a.transactions t join t.item i where i.itemId = :keyword group by i.itemId");

query.setParameter("keyword", ID);
transaction.commit();
if (query.uniqueResult() == null || query.list().isEmpty()) {
quantity = 0.0;
}
else{
quantity = Double.valueOf(query.uniqueResult().toString());

}}catch (HibernateException e) {
if (transaction != null) {
transaction.rollback();
}

}finally{
session.close();
return quantity;
}}

所以我的问题是,当我尝试将 calculateQuantity() 的结果与 Double 值相等时,为什么我得到 0? 并且如何使 itemquantity < limitvalue if 语句有效(前者应该是 Double/double,后者应该是 Integer/int)?

最佳答案

很可能是下的分支

    if(query.uniqueResult() == null || query.list().isEmpty())

正在开火。这意味着您的查询存在问题,这超出了此问题的范围。

以下应该有效:

    if(itemquantity < limitvalue)

因为 Java 支持在不显式转换的情况下对不同数值类型进行比较。 double 和 int 都属于该类别。

关于java - 将 Double 与方法中计算出的 Double 值相等会导致 0.0?可能是什么问题呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54830297/

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