# Problems with 2d arrays

• 02-25-2013, 08:34 PM
panagior
Problems with 2d arrays
Hello guys!
I have a 2d array with students and their marks! i have to calculate the averge for each student. The program compiles but the average remains 0. please help!!

public double calculateResponseAverage(String filename)
{

int col=10;
int row =8;

array = new int[row][col];

double avg=0;
for (int i=0; i<array.length; i++)
{
int sum=0;
for (int j=0; j<array[0].length; j++)
{
sum +=array[0][j];

}
avg = avg/array[0].length;
avg += sum;
}

return avg;
• 02-25-2013, 08:46 PM
jim829
Re: Problems with 2d arrays
First, it is best to put your formatted code between [code][/code] tags.

Code:

``` public double calculateResponseAverage(String filename)  {             int col=10;           int row =8;             array = new int[row][col];                   double avg=0;               for (int i=0; i<array.length; i++)               {                   int sum=0;                   for (int j=0; j<array[0].length; j++)                   {                       sum +=array[0][j];                     }                     avg = avg/array[0].length;                     avg += sum;               }               return avg;    }```

I believe you need to change your row index from 0 to i.

Jim
• 02-25-2013, 09:00 PM
panagior
Re: Problems with 2d arrays
Nothing happened :/ and i have another method called results...how do i call the average method in the results method so the average of each student appears next to its grades??

public void displayResults()
{

System.out.println( "Responses for" );
for(int i=0; i<=7; i++)

{

System.out.print("#" + (i+1) + " ");
for (int j = 0; j <= 9; j++)
{

System.out.print(array [i][j]);

}
System.out.println();

}

}
• 02-25-2013, 09:18 PM
jim829
Re: Problems with 2d arrays
You are also using ints. To calculate averages you need to use double to preserve the decimals. And you call your first method with a filename argument which isn't used. And you dividing avg by the number of entries, not the sum.

Jim
• 02-25-2013, 09:48 PM
panagior
Re: Problems with 2d arrays
ohhh...let me try that