gpt4 book ai didi

java - 使用 for 循环迭代项目列表

转载 作者:行者123 更新时间:2023-12-01 19:37:34 26 4
gpt4 key购买 nike

我已尝试迭代列表,但只获取列表的最后一个条目。我想迭代列表,将列表中的每个“利润”项目添加到 current_profit终于能够返还累计的current_profit 。方法getFinanceList()返回大小为 2 的列表,如图所示。

这是我的调试日志。它显示了从我的代码中的方法返回的大小为 2 的列表。使用getFinanceList() .

 ((FinanceRepository)this).financeList = {ArrayList@6012}  size = 2
this = {FinanceRepository@6004}
current_expenditure = 0
current_income = 0
current_profit = -1000
farmerApp = {BoxStore@6010}
financeBox = {Box@6011}
financeList = {ArrayList@6012} size = 2
0 = {Finance@6025}
__boxStore = {BoxStore@6010}
category = "farm"
finance_type = "Income"
id = 1
name = "jembe"
notes = "hdgsbsbsb.."
payment_type = "Cash"
profit = {Integer@6032} 500 //this profit
quantity = "5"
total_amount = "500"
total_expenditure = {Integer@6035} 0
total_income = {Integer@6036} 500
transaction_date = "17-7-2019"
user = {ToOne@6038}
mCallbacks = null
shadow$_klass_ = {Class@4418} "class
com.example.e_farmer.models.Finance"
shadow$_monitor_ = -2069821990
1 = {Finance@6026}
__boxStore = {BoxStore@6010}
category = "farm"
finance_type = "Expenditure"
id = 2
name = "spade"
notes = "bdhxhdd"
payment_type = "Cash"
profit = {Integer@6045} -1000 //And this profit
quantity = "5"
total_amount = "1000"
total_expenditure = {Integer@6048} 1000
total_income = {Integer@6049} 0
transaction_date = "18-7-2019"
user = {ToOne@6051}
mCallbacks = null
shadow$_klass_ = {Class@4418} "class
com.example.e_farmer.models.Finance"
shadow$_monitor_ = -1997268469
shadow$_klass_ = {Class@5986} "class
com.example.e_farmer.repositories.FinanceRepository"
shadow$_monitor_ = -2070028009
current_profit = -1000

这就是我的代码。请注意,Finance 类是我的模型类

   public MutableLiveData<Integer> getProfit() {

//the method getFinanceList returns a financeList of size 2 as illustrated above in the debug code.

getFinanceList();

int current_profit = 0;

for (int i = 0; i < financeList.size(); i++) {
Finance finance = financeList.get(i);
current_profit =+finance.getProfit();
}

Log.d(TAG, "getProfit: " + current_profit);

MutableLiveData<Integer> profit_data = new MutableLiveData<>();
profit_data.setValue(current_profit);

return profit_data;
}

我期望 current_profit 获得第一项和第二项的利润,总计为 500 + (-1000) = - 500,但我只获得最后一项 (-1000)。

最佳答案

您将 current_profit =+finance.getProfit() 写为 current_profit += Finance.getProfit()。您只需分配该值,并调用一元 + 即可,这不会执行任何操作。将一个值添加到前一个值的运算符是+=

关于java - 使用 for 循环迭代项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56887809/

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