簡體   English   中英

數字金字塔,無法將數字打印到左側

[英]Number pyramid, can't get numbers to print out to the left

我需要一個完整的金字塔,但我只能得到它的右側。 假設看起來像這樣,示例輸出為 4:

    1
   212
  32123
 4321234

我還是 Java for 循環的新手,所以我嘗試過負增量,但這不起作用是否有一種方法可以反向打印它?

import java.util.Scanner;
public class Pyramid {
    public static void main(String [] args) {
        System.out.println("Enter a number 1 to 15");
        Scanner input = new Scanner(System.in);
        int input1 = input.nextInt();
        if (input1 >= 1 && input1 <=15) {
            for(int column =1; column <input1; column++) {
                for(int row = 1; row < column; row++) {
                    System.out.print(row + " ");
                }
                System.out.print(column);
            System.out.println();
            }

        }
    }
}

您需要更多循環,並且您逐行工作,而不是逐列工作,因此外部循環應使用row

內部循環用於:

  • 打印空格
  • 打印數字是降序直到 1 (exlude)
  • 打印數字從 1 升序
for(int row = 1; row <= input1; row++) {
    for(int space = 0; space < input1-row; space++) {
        System.out.print(" ");
    }
    for(int desc = row; desc > 1; desc--) {
        System.out.print(desc);
    }
    for(int asc = 1; asc <= row; asc++) {
        System.out.print(asc);
    }
System.out.println();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM