Loading...
Logo
Processing Forum

Sum Array List

in Programming Questions  •  2 years ago  
Is it possible to sum the values inside an Array List? If so how.
Thanks,
buzz

Replies(4)

Re: Sum Array List

2 years ago
For example:
Copy code
  1. int total = 0;
  2. for (int n : listOfIntegers)
  3. {
  4.   total += n;
  5. }
  6. println(total);

hey phi.lho, thanks for your answer :)
it works well when its an array like:

  float sumHourAngle()
  {
    float angleHourSum = 0;   
    for(int i = 0; i < 24; i++)
    {   
        angleHourSum += hourAngle[i];
      }   
    return angleHourSum;
  }

however it doesn't go well when I try the same for an array list

  Array List hourAngle = new Array List();
  hourAngle.add(floats);

  float sumHourAngle()
  {
    float test[] = hourAngle.toArray();
    float angleHourSum = 0;
    for(int i = 0; i < hourAngle.size(); i++)
    {
      angleHourSum += ((float) test[i]).floatValue();
      //angleHourSum += hourAngle.get(i);
    }   
    return angleHourSum;
  }

Before I could have the floats in an array, but now the number of floats changes constantly to I am adding them to an array list first and then trying to tranform them back to an array so I can sum them. But I was wandering if that is possible and how is the correct syntax to add the values straight from the array list.
Thanks,
buzz

Re: Sum Array List

2 years ago
Copy code
  1. ArrayList<Float> hourAngles = new ArrayList<Float>();
  2. for (int i = 0; i < 60; i++)
  3. {
  4.   hourAngles.add(random(60));
  5. }

  6. float angleHourSum = 0;
  7. for (float f : hourAngles) // foreach kind of loop, with automatic unboxing
  8. {
  9.   angleHourSum += f;
  10. }
  11. println(angleHourSum);

  12. // or if you prefer the classical form
  13. angleHourSum = 0;
  14. for (int i = 0; i < hourAngles.size(); i++)
  15. {
  16.   angleHourSum += hourAngles.get(i).floatValue();
  17. }
  18. println(angleHourSum);

Sweet :) yeees, it finally runs!!! thanks a lot :)