我试图使用1D数组映射访问2D矩阵定义的值,并希望将该特定索引值存储在变量中。
矩阵包含整数值,使用2D矩阵到1D数组映射的概念我得到"二元运算符的坏操作数类型+第一类型int []和第二类型int"
导致错误的陈述是:
D = fill[ (i-1) * seq_2.length + (j-1)]
我正在尝试访问矩阵填充中的诊断值,即填充[i-1] [j-1]并希望将其存储在变量D seq_2中.length是矩阵中列的大小。 / p>
守则
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)];
}
}
答案 0 :(得分:1)
您说fill
是类型为int
的2D数组,而D
是基本类型整数...您收到错误Bad Operand Type for Binary Operator + first type int[] and second type int
,因为你试图将fill
2D数组的第一维分配给原始数据类型int ..考虑这个例子:
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
}
}
}
输出:
[I@15db9742
[I@15db9742
1
[I@6d06d69c
2
[I@6d06d69c
[I@15db9742
3
[I@6d06d69c
4
此外,如果您想计算 square 2D数组的对角线值,您可以这样做:
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);
输出:
1 2 3
4 5 6
7 8 9
Diagonal Value is: 15