0

这是我的代码:

public static int[][] arraytriangle(int lines){

    int[][] tri = new int[lines][];
    int c = 1; // incremented number to use as filler
    for (int i = 0; i < lines; i++){
        for (int j = 0; j <= i; j++){
        tri[i] = new int[i+1]; // defines number of columns
            tri[i][j] = c;
            System.out.print(c + " ");
            c++; // increment counter
        }
        System.out.println(); // making new line
    }
    System.out.println(Arrays.deepToString(tri));
    return tri;

arraytriangle(3) 给出:

1

2 3

4 5 6

[[1], [0, 3], [0, 0, 6]]

所以程序打印正确(1,2,3...),但是当我使用 deepToString 时矩阵值不正确。是什么赋予了?

4

1 回答 1

5

本次作业

tri[i] = new int[i+1];

必须在外循环内但在内循环外发生。目前,您的内部循环不断重新分配tri[i],因此只有最后一项仍然分配给deepToString

于 2013-10-29T00:48:53.350 回答