Java - 打印唯一的数字序列

我一直试图找到一种方法来打印具有特定数字序列的倒金字塔。所需的顺序如下以及我目前拥有的。


提示要求编写一个方法,该方法接受两个数字并创建一个倒金字塔,其中第一行的长度为第一个整数,并从第二个输入的数字开始。然后只有在达到 9 后才让序列从 1 开始。


    Needed:                Currently Have:


    1 2 4 7 2 7 4              1 2 3 4 5 6 7

      3 5 8 3 8 5                8 9 1 2 3 4

        6 9 4 9 6                  5 6 7 8 9

          1 5 1 7                    1 2 3 4

            6 2 8                      5 6 7

              3 9                        8 9

                1                          1




    static int plotTriangle(int a, int b){


        int num = b;


        for (int row = a; row >= 0; row--){


            for (int i = a; i - row >= 0; i--){

                System.out.print("  ");

                num += (num+a-row);

                num -= 2;

            }

            for (int i = 0; i <= row; i++){

                num++;

                while (num >= 10){

                    num -= 9;

                }                

                System.out.print(num + " ");

            }

            System.out.println();

        }

        return 0;

    }

    public static void main(String[] args) {


        Scanner in = new Scanner (System.in);


        System.out.print("Enter length: ");

        int l = in.nextInt();


        System.out.print("Enter Start: ");

        int s = in.nextInt();


        int triangle = plotTriangle(l, s);

    }


ibeautiful
浏览 125回答 1
1回答

慕神8447489

试试这个:&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; int length = 7;&nbsp; &nbsp; &nbsp; &nbsp; int[][] numbers = new int[length][length];&nbsp; &nbsp; &nbsp; &nbsp; int count = 1;&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < numbers.length; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j = 0; j < (i+1); ++j) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numbers[i][j] = count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(count > 9)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < numbers.length; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j = 0; j < numbers.length; ++j) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(numbers[j][i] == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(numbers[j][i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("&nbsp; ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }这会给你你的结果。请注意,我没有在扫描仪中包含动态部分。我使用长度和起始编号作为常量。说明:在第一个循环中,我基本上只是将数字存储在一个数组中。在第二个循环中,这个数组以不同的顺序打印。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java