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

publicclass ArrayStuff2D{

publicstaticvoid main(String args[])

{

ArrayStuff2D a =new ArrayStuff2D();

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

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

}

publicdouble [][]createArray(double[][] ar)

{

double ans = 0.0;

double ans1[0] =newdouble[ar.length];// rows

double ans1[1] =newdouble[ar[0].length];

for (int r=0; r < ar.length; r++)

{

for (int c=0; c < ar[r].length; c++)

{

// Add each row total;

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

[2551 byte] By [well1a] at [2007-11-26 23:40:26]
# 1

> 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.

floundera at 2007-7-11 15:07:01 > top of Java-index,Java Essentials,New To Java...
# 2
This is presumably a typopublic double [][]createArray(double[][] ar)
TuringPesta at 2007-7-11 15:07:01 > top of Java-index,Java Essentials,New To Java...
# 3

This must be a typo too.

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

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

floundera at 2007-7-11 15:07:01 > top of Java-index,Java Essentials,New To Java...
# 4
got it.
well1a at 2007-7-11 15:07:01 > top of Java-index,Java Essentials,New To Java...