Anatoliy Nkl
Anatoliy Nkl

Reputation: 19

The operator + is undefined for the argument type(s) int, int[]

Just trying to understand what's wrong with my code. Much appreciate ur help :)

public class lab5 {
public static void main(String[] args) {
    int[][] m = new int[5][5];

    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m[i].length; j++) {
            m[i][j] = i + j;
            System.out.println(m[i][j] + " ");
        }
        System.out.println();
     }
    int sum = 0;
    for (int i = 0; i < m.length; i++)
        sum = sum + m[i];    **// here i get error "The operator + is undefined for the argument type(s) int, int[]"**
    double average = sum / m.length;

    System.out.println("Average value of array element is " + average);

}

}

Upvotes: 0

Views: 2925

Answers (2)

Alex Shesterov
Alex Shesterov

Reputation: 27535

m is a 2-dimensional array.

m[i] is a 1-dimensional array.

+ operator makes no sense if the arguments are a number (sum) and a 1-dimensional array (m[i]).


Update: to calculate the average of a 2-dimensional array, you need to have two (nested) loops. Much like you already have in the first part of your program.

int sum = 0;
int count = 0;
for (int i = 0; i < m.length; i++) {
    for (int j = 0; j < m[i].length; j++) {
        sum = sum + m[i][j];
        ++count;
    }
}
double average = ((double) sum) / count;

The code above accounts for jagged arrays, but does not handle integer overflows.


Here's an amended homework for you :) Try to simplify the code above, removing the count variable (you can do this if the 2-dimensional array is a matrix rather than a jagged array).

Try to also handle a possible integer overflow correctly (hint: change the type of sum to something bigger than int).

Upvotes: 2

ThisaruG
ThisaruG

Reputation: 3412

If you want to calculate the sum of the array, you need 2 for loops. Try this:

for (int i = 0; i < m.length; i++) {
  for (int j = 0; j < m[i].length; j++) {
    sum = sum + m[i][j];
  }
}

Upvotes: 2

Related Questions