Java中的上三角矩阵

时间:2015-11-09 11:22:31

标签: java arrays matrix

我有一个生成以下结果集的查询

rs = [51,88,93,89,91,26,51,47,47,31,67,68,46,92,39]

我的矩阵大小是5X5,我希望最终结果为上三角矩阵

51  88  93  89  91

0   26  51  47  47

0   0   31  67  68

0   0   0   46  92

0   0   0   0   39

我的代码:但不会产生所需的O / P

int rowCount = 5;
String[][] result = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
    Cell[] row = sheet.getRow(i);

    result[i] = new String[row.length];
    for (int j = 0; j < row.length; j++) {
        if(i<=j){
            result[i][j] = row[j].getContents();
            System.out.print(result[i][j] + " ");
        }else{
            result[i][j] = "0";
            System.out.print(result[i][j] + " ");
        }
    }
    System.out.print("\n");
}

您能帮助我们帮助改变代码中的内容以获得正确的矩阵。

1 个答案:

答案 0 :(得分:1)

0位于列号小于行号的单元格中。

int rowCount = 5;
int colCount = rowCount;
int[][] result = new int[rowCount][colCount];
int[] input = { 51, 88, 93, 89, 91, 26, 51, 47, 47, 31, 67, 68, 46, 92, 39};
int k = 0;
for (int row = 0; row < rowCount; row++) {
  for (int column = 0; column < colCount; column++) {
    result[row][column] = row > column ? 0 : input[k++];
  }
}