我有一个具有以下值的2D数组
1,2,3
1,0,2
0,1,2
和具有以下值的数组
0,1,2,3,4,5,6,7,8
我要实现的是首先从array [0]开始
matrix[0][0] * array[0] = result1
matrix[0][1] * array[1] = result2
matrix[0][2] * array[2] = result3
matrix[1][0] * array[0] = result4
matrix[1][1] * array[1] = result5
matrix[1][2] * array[2] = result6
matrix[2][0] * array[0] = result7
matrix[2][1] * array[1] = result8
matrix[2][2] * array[2] = result9
之后,它将返回重做循环,但是这次从array [3]开始
matrix[0][0] * array[3] = result10
matrix[0][1] * array[4] = result11
matrix[0][2] * array[5] = result12
matrix[1][0] * array[3] = result13
matrix[1][1] * array[4] = result14
matrix[1][2] * array[5] = result15
matrix[2][0] * array[3] = result16
matrix[2][1] * array[4] = result17
matrix[2][2] * array[5] = result18
之后,它将返回重做循环,但是这次从array [6]开始
matrix[0][0] * array[6] = result19
matrix[0][1] * array[7] = result20
matrix[0][2] * array[8] = result21
matrix[1][0] * array[6] = result22
matrix[1][1] * array[7] = result23
matrix[1][2] * array[8] = result24
matrix[2][0] * array[6] = result25
matrix[2][1] * array[7] = result26
matrix[2][2] * array[8] = result27
我尝试了一下,但无法实现所需的输出。请帮忙。
public class Test1 {
public static void main (String[]args) {
int matrix[][] = new int[][] {
{1,2,3},
{1,0,2},
{0,1,2}
};
int array[] = { 0,1,2,3,4,5,6,7,8 };
int count = 0;
int a = 0;
int row = 0, col = 0;
boolean done = false;
while(!done) {
for (row = 0; row < matrix.length; row++) {
for (col = 0; col < matrix.length; col++) {
a = matrix[row][col] * array[count];
if(col > 0) {
count++;
}
if(count > col && row != col) {
count = 0;
}
if(row == matrix.length-1 && col == matrix.length-1) {
count = count + 1;
}
System.out.println(count);
}
}
if(row == matrix.length-1 && col == matrix.length-1) {
count = count + 1;
}
if(count == array.length) {
done = true;
break;
}
}
}
}
最佳答案
这是您可以使用的代码:它输出每个乘法的结果以及相应的结果索引。
public static void main(String[] args) {
int matrix[][] = new int[][] { { 1, 2, 3 }, { 1, 0, 2 }, { 0, 1, 2 } };
int array[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
int globalCount = 0;
int count = 0;
int a = 0;
int row = 0, col = 0;
boolean done = false;
for (count = 0; count < array.length; count += 3) {
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
a = matrix[row][col] * array[count++];
System.out.println("Result" + globalCount++ + " " + a);
}
count -= 3;
}
}
}
输出:
Result0 0
Result1 2
Result2 6
Result3 0
Result4 0
Result5 4
Result6 0
Result7 1
Result8 4
Result9 3
Result10 8
Result11 15
Result12 3
Result13 0
Result14 10
Result15 0
Result16 4
Result17 10
Result18 6
Result19 14
Result20 24
Result21 6
Result22 0
Result23 16
Result24 0
Result25 7
Result26 16