使用 2D 数组打印右手金字塔图案

问题描述 投票:0回答:1

我想打印一个带有图案的二维数组矩阵(右半金字塔),每个位置将存储一个数字,该数字会随着位置的变化而增加。

我使用 2D 数组创建了该模式,并为每个位置分配了一个整数值,该值应随着位置的变化而增加,但某些位置的值为 0。

public class Main {
    public static void main(String[] args) {
        int[][] twoD = new int[4][4];
        int i, j, k = 0;
        for (i = 0; i < 4; i++){
            for (j = 0; j < i + 1; j++) {
                twoD[i][i] = k;
                k++;
                System.out.print(twoD[i][j] + " ");
            }
        System.out.println();
        }
    }

Output :- 
0 
0 2 
0 0 5 
0 0 0 9 

Expected Output:-
0
1 2
3 4 5
6 7 8 9
java design-patterns
1个回答
0
投票

检查二维数组上的索引。我相信当您想输入“j”时,您输入了“i”。

© www.soinside.com 2019 - 2024. All rights reserved.