使用Java在菱形图案中打印菱形图案

时间:2019-06-12 18:55:54

标签: java printing

我想打印出这样的图案,但是我无法使它起作用。我遇到的最大问题是菱形外的线条以及菱形中仅有空间的部分。我已经用不同的数字标记了我的输出,以标记区域,所以我知道谁在做什么。 我希望有人可以帮忙。

这是我的代码:

public static void main(String[] args) {

        int rows1 = 10;
        System.out.println("## Printing the pattern ##");

        for (int i=1; i<=rows1; i++)
        {
            // Print space in decreasing order övre väster hörn tomrum
            for (int j=rows1; j>i; j--)
            {
                System.out.print(" 1 ");
            }


            // Print star in increasing order övre inre delen av triangeln tomrum
            for (int k=1; k<=(i * 2) -1; k++)
            {
                if( k == 1 || k == (i * 2) -1)
                    System.out.print("*");
                else
                    System.out.print(" 2 ");
            }
            System.out.println();
        }
        for (int i=rows1-1; i>=1; i--)
        {
         // Print space in increasing order nedre västra härnet tomrum
            for (int j=rows1-1; j>=i; j--)
            {
                System.out.print(" 3 ");
            }
            // Print star in decreasing order nedre inre delen av triangeln
            for (int k=1; k<=(i * 2) -1; k++)
            {
                if( k == 1 || k == (i * 2) -1 )
                    System.out.print("*");
                else
                    System.out.print(" 4 ");
            }


            System.out.println();
        }

}

How I want it to look or near it

1 个答案:

答案 0 :(得分:0)

该类在图片中打印图像。 基本思想是,您使用菱形的中线(的左侧)来创建表单的其余部分。

public class Diamond {

    private String base;

    public Diamond(String base) {
        this.base = base;
    }

    private String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }

    public void print() {

        int l = base.length();
        int c = (l/2)-1;

        String[] diamond = new String[l-1];
        diamond[c] = base + " " + reverse(base);

        String next = "/ " + base;
        for (int i = 1; i < l/2; i++) {

            String center = " ";
            if (next.endsWith("  ") == false) {
                center = "O";
            }

            next = next.substring(0, l);
            String bottom = next.replace('/', '\\');
            String bottomRight = reverse(next);
            String right = bottomRight.replace('/', '\\');

            diamond[c-i] = next + center + right;
            diamond[c+i] = bottom + center + bottomRight;

            next = "  " + next;
        }

        for (String line : diamond) {
            System.out.println(line);
        }
    }

    public static void main(String[] args) {
        new Diamond("  O O O O O     O O O       ").print();
    }
}