有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将多维数组的值正确保存到数组中?

下一个代码创建一个名为“arista”的随机多维数组,并用整数填充md数组的每个插槽

然后,它打印出来。您可以看到插槽中是如何填充整数的。 然后我尝试创建一个名为“lista”的数组,它应该是一个包含多维数组中存储的所有值的列表,方法是键入:

System.out.printf(Arrays.toString(lista)); 

但结果并不是我所期望的。数组“lista”中仅显示“arista”的最后一行,而数组“lista”插槽的其他部分为零

我怎样才能纠正这个问题?怎么了

完整的代码是:

public static void main(String[] args) {

    int renglones = (int) (Math.random() * 5) + 5;
    int columnas = (int) (Math.random() * 5) + 5;

    int[][] arista = new int[renglones][columnas];

    int[] lista;
    lista = new int[renglones * columnas];
    int k = 1;  

    for (int i=0; i < renglones; i++ ){
        for (int j=0; j < columnas; j++) {

        arista[i][j] = k++;
        lista[j] = arista[i][j];

        }

    }

        for (int i = 0; i < renglones; i++) {

        for (int j = 0; j < columnas; j++) {
            System.out.printf("[%d][%d] = %d \n", i, j, arista[i][j]);
        }
        System.out.println();
    }

        System.out.printf(Arrays.toString(lista)); 


}

共 (1) 个答案

  1. # 1 楼答案

    重新使用j作为lista的索引是不正确的。当j0重新开始时,它将覆盖第一个j条目的内容,只在末尾留下最后一行

    i乘以j也行不通;当其中一个为0时,您将覆盖第一个条目,因为您计算的索引将为0

    i0变为1时,您希望从超过第一个columnas项的索引号开始,而不是从0开始。当i1变为2时,您希望从索引2*columnas开始

          1st row                   2nd row  
    [0][1]...[columnas - 1] [columnas][columnas + 1] ... [2*columnas - 1] ...
    

    i乘以columnas,然后加j得到索引

    lista[i*columnas + j] = arista[i][j];