Mazz
Mazz

Reputation: 257

add values in a array list

I have the following ArrayList

ArrayList<double[]> db_results = new ArrayList<double[]>(); 

Which is populated by the following loop

double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
    double val = Double.parseDouble(i);
    nums[i] = val;        
}
db_results.add(nums);

How can i add the values from the same position in each array to make another array?? So 1+1+1=3 would be position one of the new array 2+2+2=6 would be position two of the new array and 3+3+3=9 would be position three of the new array??

Cheers

Upvotes: 0

Views: 284

Answers (3)

user370305
user370305

Reputation: 109237

Either a java math function or a nested loop its for your answer. Try yourself its just a mathematical calculation.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

This might be what you're looking for:

double[] newArray = new double[3];
for (double[] array : db_results) {
    for (int i = 0; i < 3; ++i) {
        newArray[i] += array[i];
    }
}

It will work after db_results has been populated. You can also compute the sum array at the same time that db_results is being populated using slukian's method.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718708

A nested loop would do it.

I would encourage you to take the time to do a Java tutorial or read a textbook. This is really basic stuff, and you'd do better learning the language properly than learning by trial and error interspersed with random SO questions.


By the way, this line from your code won't compile:

double val = Double.parseDouble(i);

The i variable is declared as an int and the parseXxx methods take a String argument. To convert an int to double, just assign it:

double val = i;

Upvotes: 2

Related Questions