关于在Java中打印“数字”三角形图形的汇总

2023-12-17 11:29:04

之前写过一篇利用*打印三角形汇总,网友需要查看可以去本专栏查找之前的文章,这里利用二维数组+嵌套循环打印“数字”三角形,汇总如下,话不多说,直接上代码:

/**
 * 打印如下数字三角形图形
 */
public class Work {
    public static void main(String[] args) {
        int num = 5;
        /**
         * 打印如下图形:
         * 	1
         * 	22
         * 	333
         * 	4444
         * 	55555
         */
        int[][] arr1 = new int[num][];
        for (int i = 0; i <= arr1.length - 1; i++) {
            arr1[i] = new int[i + 1];
            for (int j = 0; j <= arr1[i].length - 1; j++) {
                arr1[i][j] = i + 1;
                System.out.print(arr1[i][j]);
            }
            System.out.println();
        }

        System.out.println();

        /**
         * 打印如下的效果
         * 	    1
         * 	   22
         *    333
         * 	 4444
         * 	55555
         */
        int[][] arr2 = new int[num][];
        for (int i = 0; i <= arr2.length - 1; i++) {
            arr2[i] = new int[i + 1];
            for (int j = 0; j < num - i - 1; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= arr2[i].length - 1; j++) {
                arr2[i][j] = i + 1;
                System.out.print(arr2[i][j]);
            }
            System.out.println();
        }

        System.out.println();

        /**
         * 打印如下的效果
         * 	11111
         * 	2222
         *  333
         * 	44
         * 	5
         */
        int[][] arr3 = new int[num][];
        for (int i = 0; i <= arr3.length - 1; i++) {
            arr3[i] = new int[num - i];
            for (int j = 0; j <= arr3[i].length - 1; j++) {
                arr3[i][j] = i + 1;
                System.out.print(arr3[i][j]);
            }
            System.out.println();
        }

        System.out.println();

        /**
         * 打印如下的效果
         * 	11111
         * 	 2222
         *    333
         * 	   44
         * 	    5
         */
        int[][] arr4 = new int[num][];
        for (int i = 0; i <= arr4.length - 1; i++) {
            arr4[i] = new int[num - i];
            for (int j = 0; j <= i - 1; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= arr4[i].length - 1; j++) {
                arr4[i][j] = i + 1;
                System.out.print(arr4[i][j]);
            }
            System.out.println();
        }
    }
}

?idea中运行效果如下:

文章来源:https://blog.csdn.net/jnbbwyth/article/details/135042528
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。