0

我正在尝试编写一种方法,该方法使用我创建的列表来填充二维数组。请原谅我,因为这显然是非常基本的 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);   
}

}

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

4

1 回答 1

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++];
        }
    }
}

如果列表是列优先顺序,只需颠倒循环嵌套的顺序即可。

于 2013-06-10T03:25:11.593 回答