[英]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);
}
}
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.