# Thread: Problems with 2d arrays

1. Member Join Date
Feb 2013
Posts
3
Rep Power
0

## 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.length; j++)
{
sum +=array[j];

}
avg = avg/array.length;
avg += sum;
}

return avg;  Reply With Quote

2. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## Re: Problems with 2d arrays

First, it is best to put your formatted code between [code][/code] tags.

Java 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.length; j++)
{
sum +=array[j];

}
avg = avg/array.length;
avg += sum;
}

return avg;
}```

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

Jim  Reply With Quote

3. Member Join Date
Feb 2013
Posts
3
Rep Power
0

## 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();

}

}  Reply With Quote

4. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## 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
Last edited by jim829; 02-25-2013 at 09:25 PM.  Reply With Quote

5. Member Join Date
Feb 2013
Posts
3
Rep Power
0

## Re: Problems with 2d arrays

ohhh...let me try that  Reply With Quote

2d array, average, java 