Results 1 to 5 of 5
Thread: Problems with 2d arrays
- 02-25-2013, 07:34 PM #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[0].length; j++)
{
sum +=array[0][j];
}
avg = avg/array[0].length;
avg += sum;
}
return avg;
- 02-25-2013, 07:46 PM #2
Senior Member
- Join Date
- Jan 2013
- Location
- United States
- Posts
- 896
- Rep Power
- 1
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[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.
JimThe Java™ Tutorial
YAT -- Yet Another Typo
- 02-25-2013, 08:00 PM #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();
}
}
- 02-25-2013, 08:18 PM #4
Senior Member
- Join Date
- Jan 2013
- Location
- United States
- Posts
- 896
- Rep Power
- 1
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.
JimLast edited by jim829; 02-25-2013 at 08:25 PM.
The Java™ Tutorial
YAT -- Yet Another Typo
- 02-25-2013, 08:48 PM #5
Member
- Join Date
- Feb 2013
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
Problems with empty arrays (Putting
By JayP in forum New To JavaReplies: 5Last Post: 06-03-2011, 05:10 AM -
two problems with 2D arrays
By doha786 in forum New To JavaReplies: 0Last Post: 04-05-2010, 06:06 AM -
Some problems with arrays and loops
By BHCluster in forum New To JavaReplies: 3Last Post: 04-16-2008, 12:24 PM -
[SOLVED] Problems with arrays
By hayjk in forum New To JavaReplies: 3Last Post: 04-07-2008, 05:52 PM -
Problems with arrays
By Marcus in forum New To JavaReplies: 2Last Post: 07-04-2007, 08:10 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks