将列表传递到Java中的二维数组中

时间:2013-06-10 03:14:08

标签: java arrays arraylist

我正在尝试编写一个方法,该方法使用我创建的列表来填充二维数组。请原谅我,因为这显然是非常基本的Java,而且我很新。这是我的代码:

import java.util.*;

public class MagicSquare 
{
static final int rows = 4;
static final int columns = 4;
static final int listSize = 16;
static int row, col;
static Scanner console = new Scanner (System.in);

public static void createArithmeticSeq(int [] list)
{   
    int first; 
    int diff;
    //prompt user for first and diff
    System.out.println("Enter first and diff : ");
    first = console.nextInt();
    diff  = console.nextInt();
    //process to create list of 16 elements 
    for (int i=0; i<listSize; i++)
    {
        list[i]=first+i*diff;
    }
}
//this is where I'm having trouble
public static void matricize (int [] list, int [][] matrix)
{
//loop through each row
    for (row=0; row<matrix.length; row++)
    {
    //loop through each column
        for (col=0; col<matrix[row].length; col++)
        {
        //populate matrix with values from list

                matrix[row][col]=**????**;
        }
    }
}
public static void printMatrix(int [][] matrix)
{

    for (row=0; row < matrix.length; row++)
    {
        for (col=0; col < matrix[row].length; col++)
            System.out.printf("%2d" + " ", matrix[row][col]);

        System.out.println();
    }
    //ToDo
}

public static void reverseDiagonal(int [] [] matrix)
{
    //ToDo
}

public static void magicCheck(int [] list, int [] [] matrix)
{
    //ToDo
}

public static void main (String [] args)
{
    int [] list = new int [listSize];
    int [] [] matrix = new int [rows] [columns];
    createArithmeticSeq (list);
    matricize(list, matrix);
    printMatrix(matrix);
    reverseDiagonal(matrix);
    printMatrix(matrix);
    magicCheck(list, matrix);   
}

}

显然,请忽略我还没有达到的方法。我只需要先弄清楚这个。

1 个答案:

答案 0 :(得分:0)

看起来列表将矩阵元素存储在线性数组中,并且您希望将数据重新组织为matricize方法中的矩阵。

最简单的方法是为列表保留一个单独的索引,并在填充矩阵时递增它。如果列表以行主顺序存储矩阵元素,则可以执行以下操作:

public static void matricize (int [] list, int [][] matrix)
{
    int listIndex = 0;
    //loop through each row
    for (row=0; row<matrix.length; row++)
    {
        //loop through each column
        for (col=0; col<matrix[row].length; col++)
        {
            //populate matrix with values from list
            matrix[row][col] = list[listIndex++];
        }
    }
}

如果列表按列主顺序排列,只需颠倒循环嵌套的顺序即可。