简体   繁体   中英

Bad operand type for binary operator + first type int[] and second type int

I am trying to access the value of the 2D matrix defines using the 1D array mapping and want to store that specific index value in a variable.

The matrix contains the integer values, on using the concept of 2D matrix to 1D array mapping i am getting the error of "Bad Operand Type for Binary Operator + first type int[] and second type int"

The statement in which the error is cause is:

D = fill[ (i-1) * seq_2.length + (j-1)]

I am trying to access diagnol value in the matrix fill ie, fill[i-1][j-1] and wants to store it in a variable D seq_2.length is the size of the columns in the matrix.

the Code is

for (i = 1; i <= (seq_1.length); i++) {
    for (j = 1; j <= (seq_2.length); j++) {            

        D = fill[ (i-1) * seq_2.length + (j-1)];

    }
}

You're saying that fill is 2D array of type int , and D is a primitive type integer... you're getting the error Bad Operand Type for Binary Operator + first type int[] and second type int because you're trying to assign the first dimension of the fill 2D array to a primitive data type int.. consider this example:

int[][] array = {{1,2},{3,4}}; // 2D array of type int as an example
        for(int i=0; i<2; i++){
            System.out.println(array[i]); // this basically is getClass().getName() + '@' + Integer.toHexString(hashCode())
            for(int j=0; j<2; j++){
                System.out.println(array[j]); 
                System.out.println(array[i][j]);// this prints out the actual value at the index 
            }       
        }       
    }

The Output:

[I@15db9742
[I@15db9742
1
[I@6d06d69c
2
[I@6d06d69c
[I@15db9742
3
[I@6d06d69c
4

Furthermore, if you want to calculate the diagonal value of a square 2D array, you can do for example:

int[][] array = {{1,2,3},{4,5,6}, {7,8,9}};
int diagonalSum = 0;
for(int i=0; i<3; i++, System.out.println()){
     for(int j=0; j<3; j++){
        System.out.print(array[i][j]+"\t");
        if(j==i){
            diagonalSum+=array[i][j];
        }
     }  
}   
System.out.println("\nDiagonal Value is: " + diagonalSum);

The Output:

1   2   3   
4   5   6   
7   8   9   

Diagonal Value is: 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM