如何打印随机数菱形?

2023-12-30

有人可以帮我完成这个数字钻石吗?我打印了钻石的右侧,但在打印左侧时遇到了问题。如果有人可以提供帮助,我将非常感激。 我对我的代码做了一些更改。我现在需要我的代码在菱形中间打印一列而不是两列。

public class NumericDiamond {
    public static void main(String[] args) {
       /*
                   1         1
                4  3  4      2
             4  4  5  7  4   3
                5  3  5      4
                   4         5
        */
        int noOfColumns = 1;
        int noOfSpaces = 3;
        int start = 0;
        for (int i = 1; i <= 5; i++) {
            for (int j = noOfSpaces; j >= 1; j--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= noOfColumns; j++) {
                System.out.print(noOfColumns);
            }
            if (i < 5) {
                start = i;
            } else {
                start = 8 - i;
            }

            System.out.print(start + " ");
            start--;

            System.out.println();
            if (i < 3) {
                noOfColumns = noOfColumns + 2;
                noOfSpaces = noOfSpaces - 1;
            } else {
                noOfColumns = noOfColumns - 2;
                noOfSpaces = noOfSpaces + 1;
            }
        }
    }
}

当你在屏幕上写东西时,请按行思考。 在第一行和最后一行中,您打印 1 个随机数。在第二行和第四行中,打印 3 个随机数。在中间行,打印 5 个随机数。 您可以使用制表符或空格将数字放置到其位置。

Random rnd = new Random();
for(int i = 0; i < 5; i++) {
    if(0 == i || 4 == i) System.out.println("\t\t" + (rnd.nextInt(5)+1) + "\t\t\t" + (i+1));
    if(1 == i || 3 == i) System.out.println("\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t\t" + (i+1));
    if(2 == i) System.out.println((rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (i+1));
}

像这样的东西。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何打印随机数菱形? 的相关文章