繁体   English   中英

在 Java 中创建此数字模式

[英]Creating this number pattern in Java

我正在尝试根据正 integer 的用户输入使用 for 循环和嵌套 for 循环在 java 中创建一个模式。

这是一个例子:

用户输入 = 5

Output:

5 5 5 5 5 5 5 5 5 
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5 
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5

这是我到目前为止所拥有的。 我得到了一个整数列表,但我无法从此处找到 go 的位置来获取上述模式。 我得到的只是“5 5 5 5 5 4 4 4 4 3 3 3 2 2 1”

System.out.print("Enter the value of n: ");
int n = scan.nextInt();
for (int row = 1; row <= n; row++) { //rows
    for (int col = 1; col <= n; col++) { //columns
        if (n - col + 1 <= n - row + 1 && row <= n && col <= n) { //what to print
            System.out.print(n - row + 1 + " ");
        } else if (n - col + 1 <= n - row + 1 && row <= n && col <= n) {
            System.out.print(n - row + 1 + " ");
        }
    }
}

在这段代码中,我镜像了列,然后镜像了行。 从镜像我的意思是首先创建数据的镜像。

首先将数据写入列(左侧),然后镜像该列,因此我得到该列的右侧。

在将数据写入上面的行然后镜像上面的行后,我得到了下面的行。

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class Pattern {
    static final PrintStream out = System.out;

    public static void displayPattern(int n) {
        final int arr[][] = new int[n * 2 - 1][];

        for (int i = 0; i < arr.length; i++)
            arr[i] = new int[n * 2 - 1];

        final List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int current = n - i;
            list.add(current);
            for (int j = 0; j < list.size(); j++) {
                arr[i][j] = list.get(j);
            }
            int remainings = n - list.size();
            for (int j = list.size(), count = 0; count < remainings; j++, count++) {
                arr[i][j] = current;
            }

            //writing data to right side of the columns(mirroring columns)
            for (int j = n, count = 1; j < arr[i].length; j++, count++)
                arr[i][j] = arr[i][j - count * 2];
        }
        //writing data to bottom half of the rows(mirroring rows)
        for (int i = n, count = 1; i < n * 2 - 1; i++, count++) {
            for (int j = 0; j < n * 2 - 1; j++)
                arr[i][j] = arr[i - count * 2][j];
        }


        for (int a[] : arr) {
            for (int b : a)
                out.print(b + " ");
            out.println();
        }

    }

    public static void main(final String... $) {
        displayPattern(5);
    }
}

Output:

5 5 5 5 5 5 5 5 5 
5 4 4 4 4 4 4 4 5 
5 4 3 3 3 3 3 4 5 
5 4 3 2 2 2 3 4 5 
5 4 3 2 1 2 3 4 5 
5 4 3 2 2 2 3 4 5 
5 4 3 3 3 3 3 4 5 
5 4 4 4 4 4 4 4 5 
5 5 5 5 5 5 5 5 5 

暂无
暂无

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

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