简体   繁体   English

我如何在 java 中使用锯齿状数组制作这个矩阵示例

[英]How can i make this matrix example with jagged array in java

I've this codes:我有这个代码:

public class matrixExample {
    public static void main(String[] args)   {

        int m[][] = new int[5][5]; 

        int count = 1;  
        for (int i=0; i<m.length; i++) 
            for(int j=0; j<i+1; j++) 
                m[i][j] = count++; 
       

        for (int i=0; i<m.length; i++)
        {
            for (int j=0; j<m[i].length; j++)
                System.out.print(m[i][j] + "  "); 
            System.out.println();
        }
    }
}

And output:和 output:

电流输出

How can I do as in the screenshot below?我该怎么做,如下面的截图所示?

我需要

int size = 5;
int[][] m = new int[size][size];
int count = 1;
for (int i = 0; i < size; ++i)
    for (int j = size - i - 1; j < size; ++j)
        m[i][j] = count++;

You may populate the matrix as suggested in saka1029's answer above and then print it using formatted output:您可以按照上面saka1029 的回答中的建议填充矩阵,然后使用格式化的 output 打印它:

    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m[i].length; j++) {
            System.out.printf(" %2d ", m[i][j]);
        }
        System.out.print('\n');
    }

Or, it is possible to keep "normal" matrix, and change only its output:或者,可以保持“正常”矩阵,仅更改其 output:

public static void main(String []args){
    int m[][] = new int[5][5]; 

    int count = 1;
    // keeping initial array as is
    for (int i=0; i<m.length; i++) 
        for(int j=0; j<i+1; j++) 
            m[i][j] = count++; 
           
    for (int i = 0; i < m.length; i++) {
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < m[i].length; j++) {
            if (m[i][j] > 0) {
                sb.append(String.format(" %2d ", m[i][j]));
            } else {
                sb.insert(0, String.format(" %2d ", m[i][j]));
            }
        }
        System.out.println(sb.toString());
    }
}

Output in both cases is identical:两种情况下的 Output 是相同的:

  0   0   0   0   1 
  0   0   0   2   3 
  0   0   4   5   6 
  0   7   8   9  10 
 11  12  13  14  15 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM