0

I have a program where i have to find the average for each student score from a text file and display it as a 2D array.

I am stuck - all I accomplish every time is getting the average for each row or column, but i have to find the average for each value in the text file.

For example: 76 / 48 = 1.5 (rounding off to 1 decimal)

Snippet of text file

Here my code:

public void studentAverage(double average) throws 
FileNotFoundException 
{
    File infile= new File("qdata.txt");
    Scanner sc = new Scanner(infile);
    double rowNum = 0;
    for (int row = 0; row < arr.length; row++) 
    {
        for (int col = 0; col < arr[row].length; col++) 
        {
            //Im stucked here 
           rowNum += arr[row][col];

        }
        average = rowNum / arr[row].length;
        System.out.println("StudentAverage is: "+average);
        rowNum = 0;
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • What does a line in your file look like? Also, are you sure it's an average you want? – Joakim Danielson Mar 19 '19 at 09:34
  • I'm having a hard time understanding what you're after. If you don't want to get the average per column, row or the entire array, how is the average defined then? Where does that `76 / 48` example come from? – Thomas Mar 19 '19 at 09:35
  • I gave a snippet of my text file with the values – nadine jansen Mar 19 '19 at 09:37
  • Yes you did but the explanation is hard to understand. Let me try: that 76 is the first element in the file, while 48 is the number of all elements? If that is correct, then you'd need to do 2 things: 1) read the file and create the 2d array. While doing that count the number of elements (if the rows might have different lengths). 2) Once you know the number of elements iterate over the array again and do the calculation, i.e. `array[x][y] /= numberOfElements;` (or however you want it rounded). – Thomas Mar 19 '19 at 09:40
  • That is meant to do `elementValue / numberOfElements` for each element individually. As I said it is just a _guess_ because you did _not_ actually specify what "average" you are after (however column, row or total average seem not be what you want). From all the answers and guesses we've provided and all the times you stated "that is not what I want" you should realize that your requirement isn't clear. So please provide some understandable examples (e.g. what values you'd use to calculate that "average" and what those values mean or where they come from). – Thomas Mar 19 '19 at 10:10

5 Answers5

1

The average for each value in the entire grid is just a single number (I think). So, all you need to is to take the running sum and then divide by the number of cells:

double sum = 0.0d;

for (int row = 0; row < arr.length; row++) {
    for (int col = 0; col < arr[row].length; col++) {
       sum += arr[row][col];
    }
}

int size = arr.length*arr[0].length;
double average = sum / size;
System.out.println("StudentAverage is: " + average);

In my calculation of the size, which is the total number of students, I am assuming that your 2D array is not jagged. That is, I assume that each row has the same number of columns' worth of data.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You could use streams for this.

To get the overall average

double average = Arrays.stream(arr)
    .flatMapToInt(Arrays::stream)
    .average();

And to get the average per row:

double[] averagePerRow = Ararys.stream(arr)
    .map(Arrays::stream)
    .mapToDouble(IntStream::average)
    .toArray();

This works for any 2D int array, jagged or not.

Lino
  • 19,604
  • 6
  • 47
  • 65
  • I have the over all average in my code. I need the average for each element that are in the text file. – nadine jansen Mar 19 '19 at 10:08
  • 1
    @nadinejansen please clarify *average for each element* what do you mean with *element*? An actual value or a colum or a row? – Lino Mar 19 '19 at 10:10
  • @nadinejansen read my comment again, **clarify** what you mean with *value* and *elements* – Lino Mar 19 '19 at 10:26
0

Check this Link - How to find average of elements in 2d array JAVA?

public class AverageElements {
private static double[][] array;

public static void main (String[] args){

    //  Initialize array
    initializeArray();

    //  Calculate average
    System.out.println(getAverage());
}   

private static void initializeArray(){
    array = new double[5][2];
    array[0][0]=1.1;
    array[0][1]=12.3;
    array[1][0]=3.4;
    array[1][1]=5.8;
    array[2][0]=9.8;
    array[2][1]=5.7;
    array[3][0]=4.6;
    array[3][1]=7.45698;
    array[4][0]=1.22;
    array[4][1]=3.1478;
}

private static double getAverage(){
    int counter=0;
    double sum = 0;
    for(int i=0;i<array.length;i++){
        for(int j=0;j<array[i].length;j++){
            sum = sum+array[i][j];
            counter++;
        }
    }

    return sum / counter;
}
}
0
double sum=0;
int size=0;
for (int row = 0; row < arr.length; row++) {
    for (int col = 0; col < arr[row].length; col++) {
       sum += arr[row][col];
    }
    size+=arr[row].length;
}

double average = sum/size;
System.out.println("StudentAverage is: "+average);
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
0

I would use List for this

public void studentAverage() throws FileNotFoundException {
    File infile= new File("qdata.txt");
    Scanner sc = new Scanner(infile);
    double rowNum = 0;
    List<List<Integer>> grades = new ArrayList<>();
    double totalCount = 0.0;
    while (sc.hasNext()) {
        List<Integer> row = new ArrayList<>();
        Scanner lineScanner= new Scanner(sc.nextLine());
        while (lineScanner.hasNextInt()) {
            row.add(lineScanner.nextInt());
        }
        grades.add(row);
        totalCount += row.size();
    }

    int index = 0;
    for (List<Integer> list : grades) {
        for (Integer grade : list) {
          System.out.println("Student average is " + (double)Math.round(grade.doubleValue() / totalCount * 10) / 10);
        }
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52