首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

求解编写一个显示金字塔的程序,该怎么解决

2012-04-13 
求解编写一个显示金字塔的程序如何实现输入一个1--15之间的数字,然后显示一个金字塔形状的图案。eg: 512 1

求解编写一个显示金字塔的程序
如何实现输入一个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();        }    }} 

热点排行