4 Replies Latest reply: Apr 1, 2007 8:55 PM by 807599

# 2D arrays

createArray(): This method must create a 2D array of doubles that has 2 rows and 3 columns. Fill in each array element with the value of 2 * it's row number plus 2 * it's column number. Then, write a nested for loop that goes through the array and adds up all the numbers, and prints the sum to the screen.

This is the code
``````public class ArrayStuff2D{

public static void main(String args[])
{
ArrayStuff2D a = new ArrayStuff2D();

double array1[][] = { {1,2,3},{4,5,6}};

double [][]sum = a.createArray(array1);
}

public double [][]createArray(double[][] ar)
{

double ans = 0.0;
double ans1[0] = new double[ar.length]; // rows
double ans1[1] = new double[ar[0].length];
for (int r=0; r < ar.length; r++)
{
for (int c=0; c < ar[r].length; c++)
{
ans1[0][r] += 2 * ar[r][c];

// Sum of each column
ans1[1][c] += 2 * ar[r][c];

ans = ans1[0][r] + ans1[1][c];
}
}
return ans;
// ans[0] contains sum of each row
// ans[1] contains sum of each col
}

}``````
This is not working?is my logic wrong
• ###### 1. Re: 2D arrays
This is not working?
This is a question. So you want us to figure out if your code works or not. Surely you can do that for yourself.

If you want some help, them perhaps a detailed explanation of not working means. I bet your code can't bake a soufle, so not working is an adequate description.

However, you are to write a method called createArray that creates, populates and returns a 2D array. So why is it accepting a 2D array as a parameter?

Also, check your assignment because I believe there should be a second method called sum that performs the calculation. Not shoved into the createArray method.
• ###### 2. Re: 2D arrays
This is presumably a typo
public double [][]createArray(double[][] ar)
• ###### 3. Re: 2D arrays
This must be a typo too.
``````double array1[][] = { {1,2,3},{4,5,6}};

double [][]sum = a.createArray(array1);``````
• ###### 4. Re: 2D arrays
got it.