問題描述:數字金字塔
輸入一個正整數n(n<16),輸出一個如圖的數字金字塔(下圖是當n=7的輸出)。不考慮輸入錯誤的情形。
要求使用Scanner作爲輸入,System.out.print作爲輸出。
程序設計:
假設輸入數字n,經過觀察能發現這樣的關係:
- 空格數與行數:空格數=n-行數;
- 左邊的數字:從行數到1;
- 右邊的數字:從2到行數。由此可寫出程序。
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for(int i = 1;i <= n; i++){
for(int j = 1; j <= n-i; j++){ //輸出左邊空格
System.out.print(" " + "\t");
}
for(int m = i; m >= 1; m--){ //輸出左邊數字
System.out.print(m + "\t");
}
for(int l = 2; l <= i; l++){ //輸出右邊數字
System.out.print(l + "\t");
}
System.out.print("\n");
}
}
}