Java 无法在1d和2d数组值之间转换

Java 无法在1d和2d数组值之间转换,java,arrays,matrix,2d,Java,Arrays,Matrix,2d,我意识到这个问题和解决方案已经解决了,但是我仍然无法让它工作 大多数示例都说,我只需要将行乘以宽度,然后添加列,这意味着4x4正方形网格中的位置(4,3)将变成(3*4+4)或16。到目前为止还不错 示例中说,为了得到坐标,我应该将索引除以x的行数,然后得到y的索引模。对于上面的例子,应该是 int x = 16 / 4; int y = 16 % 4; 但这对某些价值观有效,而对其他价值观无效。在本例中,当我在转换为索引后返回坐标时,我得到(4,0)。这是有道理的,因为4等于16,所以我肯定

我意识到这个问题和解决方案已经解决了,但是我仍然无法让它工作

大多数示例都说,我只需要将行乘以宽度,然后添加列,这意味着4x4正方形网格中的位置(4,3)将变成(3*4+4)或16。到目前为止还不错

示例中说,为了得到坐标,我应该将索引除以x的行数,然后得到y的索引模。对于上面的例子,应该是

int x = 16 / 4;
int y = 16 % 4;
但这对某些价值观有效,而对其他价值观无效。在本例中,当我在转换为索引后返回坐标时,我得到(4,0)。这是有道理的,因为4等于16,所以我肯定错过了一些基本的东西

下面是我为尝试解决这个问题而创建的一些测试Java代码。我应该提到,我的索引从1开始,所以左上角的第一个正方形是1,1,最后一个正方形是4,4

public class Test {

    int size;

    public Test(int size) {
        this.size = size;
    }

    public int toIndex(int x, int y) {
        return x * this.size + y;
    }

    public int[] toCoordinates(int index) {
        int coordinates[] = new int[2];
        coordinates[0] = index / this.size;
        coordinates[1] = index % this.size;
        return coordinates;
    }

    public static void main(String[] args) {
        int testSize = 4;
        Test test = new Test(testSize);

        for (int i = 1; i <= testSize; i++) {
            for (int j = 1; j <= testSize; j++) {
                int index = test.toIndex(i, j);
                int coordinates[] = test.toCoordinates(index);
                System.out.println(index + " == " + coordinates[0] + "," + coordinates[1]);
            }
        }
    }
}

所有数组都以0开头,请尝试以下操作:

public static void main(String[] args) {
    int testSize = 4;
    Test test = new Test(testSize);

    for (int i = 0; i < testSize; i++) {
        for (int j = 0; j < testSize; j++) {
            int index = test.toIndex(i, j);
            int coordinates[] = test.toCoordinates(index);
            System.out.println(index + " == " + coordinates[0] + "," + coordinates[1]);
        }
    }
}

看起来您在错误情况下交换了x和y。位置应该是19,而不是16

Position [4,3] in a 4x4 array is (4*4)+3 = 19
floor(19 / 4) = 4
19 % 4 = 3 

为了学习数组,我强烈建议坚持使用零索引数组,因为它们更直观地与内容在内存中的实际存储方式相关联。

左上角为0,0,右下角为3,3。0是第一个数字!我猜你的困惑源于使用单索引数组。Java使用0索引数组,我强烈建议您也这样做。就是这样!在进行计算时,我只需要将1添加到大小。我已经有一段时间没有使用过了,因为这些都是注释,所以可以用什么方式将此问题标记为已解决?从数组上的0开始是正确的。还要注意,在David的回答中,他正在打印的索引以0开头。在您的示例输出中,您的第一个索引输出是5。谢谢!是的,索引是个问题。我仍然需要1作为索引,因为它插入了其他需要它的东西,但是我通过在转换期间增加大小解决了这个问题。
0 == 0,0
1 == 0,1
2 == 0,2
3 == 0,3
4 == 1,0
5 == 1,1
6 == 1,2
7 == 1,3
8 == 2,0
9 == 2,1
10 == 2,2
11 == 2,3
12 == 3,0
13 == 3,1
14 == 3,2
15 == 3,3   (16th)
Position [4,3] in a 4x4 array is (4*4)+3 = 19
floor(19 / 4) = 4
19 % 4 = 3