错误:二元运算符的错误操作数类型' +'

时间:2016-06-27 08:52:47

标签: java

我在以下代码中收到错误,其中包含"错误:二元运算符' +'的错误操作数类型。错误出现在第sum+=arr[i]行     此代码用于计算整数矩阵的对角线差异

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[][] = new int[n][n];
        for(int a_i=0; a_i < n; a_i++){
            for(int a_j=0; a_j < n; a_j++){
                a[a_i][a_j] = in.nextInt();
            }
        }
        Solution solution= new Solution();
        solution.diagonalDifference(a,n);
    }
    public void diagonalDifference(int arr[][],int n){
        int sum=0,sum1=0,sum2=0;
        for(int i=0; i < n;i++){
            for(int j=0; j < n;j++){
                if(i==j){
                    sum1+=arr[i];//calculating sum of primary diagonal
                }
            }
        }
        for(int i=0; i < n;i++){
            for(int j=n; j >0;j--){
                 sum2+=arr[i];//calculating sum of secondary diagonal
            }
        }
        sum=Math.abs(sum1-sum2);
        System.out.println(sum);
    }
}

错误: -

Solution.java:26: error: bad operand types for binary operator '+'
                    sum+=arr[i];//calculating sum of primary diagonal
                       ^
  first type:  int
  second type: int[]
Solution.java:32: error: bad operand types for binary operator '+'
                 sum+=arr[i];//calculating sum of secondary diagonal
                    ^
  first type:  int
  second type: int[]
2 errors

1 个答案:

答案 0 :(得分:2)

arr[i]是一个数组,而不是int。

更改

sum+=arr[i];

sum+=arr[i][j];

您可能还想更改第二个循环的范围(计算辅助对角线):

    for(int i = 0; i < n; i++) {
        for(int j = n - 1; j >= 0; j--) {
             sum += arr[i][j]; //calculating sum of secondary diagonal
        }
    }