【发布时间】:2017-03-30 11:24:29
【问题描述】:
我在 Java (1.8.0.121) 中创建了以下代码,用于将 iMatrix 数组解析为 matrixOutput 之一。 运行它后,我注意到单元格 1,0 和 1,1 中出现了附加值。
有人可以建议我如何更改以避免对其他数组进行此类添加(我计划了一个通用代码,它将采用 iMatrix 数组等格式的不同数组)
公共类 Dbg {
private static int[][] matrixOutput = { { 0, 2, 0, 0, 0 },
{ 0, 0, 0, 4, 0 },
{ 1, 2, 0, 0, 5 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
{1, -1, 0, 0, 0},
{0, 1, 0, -1, 0},
{-1, 0, 1, 0, 0},
{0, -1, 1, 0, 0},
{0, 0, 1, 0, -1},
{0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;
public static void main(String[] args) {
int[][] list = new int[5][5];
for (int m = 0; m < iMatrix.length; m++) {
for (int n = 0; n < iMatrix[m].length; n++) {
if (iMatrix[m][n] == 1){
i = n;
}
if (iMatrix[m][n] == -1){
j = n;
val = n + 1;
}
list[i][j] = val;
}
}
for (i = 0; i < list.length; i++) {
for (j = 0; j < list.length; j++) {
System.out.print(list[i][j]);
}
System.out.println();
}
}
}
在 MatrixOutput 中,它给了我以下结果:
02000
12040
12005
00000
00000
当我将位置更改为 3 行和 4 行时,我看到 1,0 中的值 1 消失了。 iMatrix 中的所有值都已正确存储。
【问题讨论】:
-
请edit您的问题添加一个标签,表明您正在使用哪种编程语言。
-
这也是学习如何使用调试器的好时机
标签: java arrays multidimensional-array