简体   繁体   English

java中的数字模式程序

[英]number pattern programs in java

How to print the triangle below: 如何打印下面的三角形:

2  3  5  8  3  8
   4  6  9  4  9
      7  1  5  1
         2  6  2
            7  3
               4

First you need to start with number 2 and add one to the next one vertically 首先,您需要从数字2开始,然后垂直添加一个到下一个

My code: 我的代码:

        int d = 2, n = 6;
        for (int line=1; line <= n; line++ ) {
            for (int j = 2; j <= line; j++) {
                System.out.print("  ");
            }
            for (int k = line; k <= n; k++) {
                System.out.print(d + " ");
                    d = d + k;
                    if (d > 9) {
                        d = d - 9;
                    }
            }
            System.out.println();
        }

Result: 结果:

2 3 5 8 3 8 
  5 7 1 5 1 
    7 1 5 1 
      7 2 7 
        4 9 
          6 

The pattern is that the value of d has to be calculated initially on every new line based on the value of d in the first instance of the previous line . 所述图案是,该值d必须被基于的值的每个新行初始计算 d上一行的第一个实例 That is the part that's missed here. 这是在这里错过的部分。 You can do that by having a temp variable store the initial value of d on every line and print based on that. 你可以通过让temp变量在每一行存储d的初始值并根据它进行打印来实现。 I have used a variable tempD here, which can help print the pattern that you require. 我在这里使用了一个变量tempD ,它可以帮助打印你需要的模式。

    int d = 2, n = 6;
    int tempD = d - 1;
    for (int line = 1; line <= n; line++) {
        tempD = tempD + line;
        if (tempD > 9) {
            tempD = tempD - 9;
        }
        d = tempD;
        for (int j = 2; j <= line; j++) {
            System.out.print("  ");
        }
        for (int k = line; k <= n; k++) {
            System.out.print(d + " ");
            d = d + k;
            if (d > 9) {
                d = d - 9;
            }
        }
        System.out.println();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM