如何根据用户输入来管理加法和减法操作?

huangapple go评论76阅读模式
英文:

How to manage adding and subtracting values based on user input?

问题

我有一个看起来像这样的购物车:

标题      价格     数量     总计
商品1     20      3        60
商品2     15      2        30


总计:90

Amount 列是一个输入标签,用户可以输入他想购买的物品数量,只要用户在添加物品时一切正常,因为在后端我正在计算总和(TotalAll+=Total),问题是当用户将 Amount 设置为小于当前输入的数量时,例如将商品1从3个减少到2个,总计仍然会将这2个添加进去,值将变为 总计:130,但实际应该是70,因为现在只有2个物品。那么当 Amount 减少时,我应该如何从 TotalAll 中减去?在什么情况下?

英文:

I have a shopping cart that looks like this:

Title    Price    Amount    Total
Item1    20         3        60
Item2    15         2        30


TotalAll:90

Amount column is input tag where user can put how many items he wants to buy, and everything works as long as the user is adding items since in backend I'm doing sum total(TotalAll+=Total), the problem is when user put a smaller amount than currently entered for example for Item1 from 3 to 2 items, TotalAll will still add those 2 and value will be TotalAll:130 but it should be 70 because it's now 2 items. So how can I subtract from TotalAll when amount is reduced? In what case?

答案1

得分: 1

每当用户更改输入时,只要针对该项刷新了Total值,您可以在后端重置TotalAll值为0,无论您在哪里对所有Totals进行求和,并重新计算TotalAll值。这可能听起来效率不高,但如果您处理的项目数量很少,应该可以正常工作。

英文:

Whenever user changes the input, as long as Total value is refreshed for that item, You can reset the TotalAll value to 0 in your backend wherever you're summing all the Totals and recalculate the TotalAll value. This may sound inefficient but should work fine if you're dealing with minimal number of items.

答案2

得分: 0

这是我的解决方案:

totalAll = 0.0;
List<Article> articleList = ArticleSelectDAO.selectArticles();
for (Article a : articleList) {
    totalAll += a.getTotal();
}
在重置“totalAll”之前,我必须使用当前每个项目的总值更新数据库。然后,我将这些文章添加到列表中,遍历列表并将值添加到“totalAll”中。
英文:

This my solution:

        totalAll = 0.0;
        List&lt;Article&gt; articleList = ArticleSelectDAO.selectArticles();
        for (Article a : articleList) {
        totalAll+=a.getTotal();
        }

Before i reset totalAll i have to update database with current total value per item. Then i add those articles in List, iterate over List and add value to totalAll.

huangapple
  • 本文由 发表于 2020年7月30日 19:36:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63172357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定