填充垂直矩阵Java

时间:2015-06-13 18:25:10

标签: java arrays matrix

我正在尝试垂直填充矩阵,但缺少1行。你能帮助我吗 ?有代码。也许有一种更简单的方法来填充矩阵,但我无法找到它。

public static void main(String[]args){
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the value of matrix: ");
    int n = input.nextInt();

    int [][] matrix = new int [n][n];


    for (int i = 1; i < matrix.length; i++) {
        matrix[0][i] = matrix[0][i -1] + n;

    }

    for(int i = 1; i < matrix.length; i++){
        for (int j = 0; j < matrix.length; j++){
        matrix[i][j] = matrix[i -1][j] + 1;

        System.out.print(matrix[i][j] + " ");

        }
            System.out.println();

    }

            input.close();
}

输出: Enter the value of matrix: 4 1 5 9 13 2 6 10 14 3 7 11 15

4 个答案:

答案 0 :(得分:1)

您的行丢失了,因为您从未在第一个循环中打印它(正在初始化您的第一行的那个) - 您应该在开头有一行0 4 10 12。但是只用一个嵌套循环就可以轻松完成。

答案 1 :(得分:0)

要垂直填充矩阵,必须遍历外部循环中的列以及内部(嵌套)循环中的行。例如:

for(int j = 0; j < matrix.length; j++) {

    for(int i = 0; i < matrix.length; i++) {

        matrix[i][j] = /* The value you want to fill */;
        .../* Other stuff you wanna do */
    }
}

答案 2 :(得分:0)

有一种更简单的方法:

保持一个像count这样的变量,然后先在列上迭代矩阵然后再行:

int count = 1; // or 0 if you start with 0
int[][] a = new int[n][n];
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) {
         a[j][i] = count; // notice j first then i 
         count++;
    }

之后,您可以轻松打印出值:

for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
        System.out.println(a[i][j]);

答案 3 :(得分:0)

试试

 public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();

int [][] matrix = new int [n][n];

matrix[0][0]=0;  //you have forgotten the first value
for (int i = 1; i < matrix.length; i++) {
    matrix[0][i] = matrix[0][i -1] + n;
    //initializing the first line
}

for(int i = 1; i < matrix.length; i++){
    for (int j = 0; j < matrix.length; j++){
    matrix[i][j] = matrix[i -1][j] + 1;
    }

    // re-loop to display but this time start with i=0
   for(int i = 0; i < matrix.length; i++){
    for (int j = 0; j < matrix.length; j++){
     System.out.print(matrix[i][j] + " ");
    }

        System.out.println();

}

        input.close();
}