打印金字塔的java小程序

/**
 * Created by wangjunling on 7/14/14.
 * 打印金字塔
 */
public class PrintPyramid {

    /**
     * 打印数组
     * @param ary
     */
    private static void print(String[][] ary) {
        for (int i = 0; i < ary.length; i++) {
            for (int j = 0; j < ary[i].length; j++) {
                System.out.printf("%6s", ary[i][j]);
            }
            System.out.println();
        }
    }

    /**
     * 填充数组
     * @param ary
     * @param line
     * @param row
     */
    private static void fill(String[][] ary, int line, int row) {
        for (int j = 0; j < row; j++) {
            int a = 1;
            for (int i = Math.abs(line - j - 1); i < line; i++) {
                ary[i][j] = String.valueOf(a);
                a = a * 2;
            }
            for (int i = 0; i < Math.abs(line - j - 1); i++) {
                ary[i][j] = " ";
            }
        }
    }

    public static void main(String[] args) {
        int line = 8;
        int row = 2 * line - 1;
        String[][] pyramid = new String[line][row];
        fill(pyramid, line, row);
        print(pyramid);
    }

}
打印金字塔的java小程序_第1张图片

你可能感兴趣的:(java)