如何实现输入一个1--15之间的数字,然后显示一个金字塔形状的图案。
eg: 5
1
2 1 2
3 2 1 2 3 1
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
------解决方案--------------------
package org.lw.test;
import java.util.Scanner;
public class Test12 {
public static void main(String[] args) {
System.out.println("请输入一个1~15之间的整数:");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for(int i =1; i<=n; i++){
for(int j = 0; j<2*i-1; j++){
if(i-j>0){
System.out.print(i-j + " ");
}else{
System.out.print(j-i+2 + " ");
}
}
System.out.println();
}
}
}
------解决方案--------------------
- Java code
import java.util.Scanner;public class Test12 { public static void main(String[] args) { System.out.println("请输入一个1~15之间的整数:"); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[][] array = new int[n][2*n+1]; for (int i = 0; i < n; i++) { for (int j = n-i; j <= n + i; j++){ array[i][j]=Math.abs(n-j)+1; } } for(int i=0;i<n;i++){ for (int j = 0; j < 2*n + 1; j++){ System.out.print(array[i][j]==0?" ":array[i][j]+" "); } System.out.println(); } }}