[英]How can I get all sum of data from arraylist in a for loop?
This is the code:这是代码:
ArrayList<DailyChallengesModelFinal> dailyList = new ArrayList<>();
int selectedItems = position;
Log.d("dbKEY", String.valueOf(exDBKey));
int sum = 0;
for (int i = selectedItems; i <=0; i++) {
int points = dailyList.get(position).getPoints();
sum = sum + points; }
I'm not getting the desired result.我没有得到想要的结果。
What I wanna get is for example the array has 50,80,and 60 then it should add the values from the array.我想要得到的是例如数组有 50,80 和 60 然后它应该添加数组中的值。
try this code试试这个代码
int sum = 0;
for(int i = 0; i <=dailyList.size(); i++) {
dailyExerciseID = dailyList.get(i).getDcExerciseId();
dailyExerciseName = dailyList.get(i).getDcexerciseName();
points = dailyList.get(i).getPoints();
sum = sum + points;
}
Look at this:看这个:
for (int i = selectedItems; i <=0; i++) {
The starting value of i
is selectedItems
which is a positive number I suppose. i
的起始值是selectedItems
,我认为这是一个正数。
The limit you set for the loop to stop is i <=0
while you increase i
by i++
.您为循环设置的限制是
i <=0
而您将i
增加i++
。
This for loop will never execute.这个 for 循环永远不会执行。
Change the starting point and the condition to stop.改变起点和停止条件。
If you want to iterate through the whole list then:如果要遍历整个列表,则:
for (int i = 0; i < dailyList.size(); i++) {
If you want to iterate through the first selectedItems
items then:如果要遍历第一个
selectedItems
项,则:
for (int i = 0; i < selectedItems; i++) {
This will do your job:这将完成您的工作:
ArrayList<DailyChallengesModelFinal> dailyList = new ArrayList<>();
int selectedItems = position;
Log.d("dbKEY", String.valueOf(exDBKey));
int sum = 0;
for (int i = selectedItems; i > 0; i--)
{
int points = dailyList.get(i).getPoints();
sum += points;
}
dailyList.subList(position, dailyList.size()).stream().map(DailyChallengesModelFinal::getPoint).reduce((p1, p2) -> p1 + p2).orElse(0);
I have updated your code.我已经更新了你的代码。 Please check it.
请检查一下。
int sum = 0;
for (int i = 0; i <dailyList.size(); i++) {
dailyExerciseID = dailyList.get(position).getDcExerciseId();
dailyExerciseName = dailyList.get(position).getDcexerciseName();
sum = sum + dailyList.get(position).getPoints();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.