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

go评论14阅读模式

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

# 问题

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

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

totalAll = 0.0;
List<Article> articleList = ArticleSelectDAO.selectArticles();
for (Article a : articleList) {
totalAll += a.getTotal();
}

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.

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

go 13

go 19

go 13

go 18