如何打印中心数字金字塔?

时间:2016-02-20 05:18:00

标签: java

我想在Java中打印以下模式

java number pattern

到目前为止,我有以下代码,它打印正确的数字但我似乎无法正确居中

public class JavaNumberPatternPyramid {

    public static void printSpaces(int n) {
        for (int i = 0; i < n; i++)
            System.out.print(" ");
    }

    public static void printPadding(int x) {
        if (x < 10) {
            System.out.print("    ");
        } else if (x > 9 && x < 99) {
            System.out.print("   ");
        } else {
            System.out.print("  ");
        }
    }

    public static void main(String[] args) {

        for (int i = 1; i <= 8; i++) {
            printSpaces(8 - i);
            for (int j = 0; j < i; j++) {
                int x = (int)Math.pow(2, j);
                printPadding(x);
                System.out.print(x);
            }
            for (int j = i - 2; j >= 0; j--) {
                int x = (int)Math.pow(2, j);
                printPadding(x);
                System.out.print(x);
            }
            System.out.println();
        }

    }

}

编辑目前看起来像这样

current output

我缺少什么,我该如何居中?

2 个答案:

答案 0 :(得分:0)

public static void printSpaces(int n) {
        for (int i = 0; i < n; i++)
            System.out.print(" ");
    }

    public static void printPadding(int x) {
        if (x < 10) {
            System.out.print("   ");//3 spaces
        } else if (x > 9 && x < 99) {
            System.out.print("  ");//2 spaces
        } else {
            System.out.print(" ");
        }
    }

    public static void main(String[] args) {

        for (int i = 1; i <= 8; i++) {
            printSpaces(32 - i*4);//here you need more spaces
            for (int j = 0; j < i; j++) {

                int x = (int)Math.pow(2, j);
                printPadding(x);
                System.out.print(x);
            }
            for (int j = i - 2; j >= 0; j--) {
                int x = (int)Math.pow(2, j);
                printPadding(x);
                System.out.print(x);
            }
            System.out.println();
        }

    }

<强>输出:

                               1
                           1   2   1
                       1   2   4   2   1
                   1   2   4   8   4   2   1
               1   2   4   8  16   8   4   2   1
           1   2   4   8  16  32  16   8   4   2   1
       1   2   4   8  16  32  64  32  16   8   4   2   1
   1   2   4   8  16  32  64 128  64  32  16   8   4   2   1

答案 1 :(得分:0)

试试这个。

# Simple admin setup
from django.contrib import admin
from .models import MyModel
# Register model
admin.site.register(MyModel)
# Tweak admin site settings like title, header, 'View Site' URL, etc
admin.site.site_title = 'My App Admin'
admin.site.site_header = 'My App Admin'