控制台中的钻石绘图

时间:2014-01-10 21:52:18

标签: java console

我几天来一直在研究一个问题,在控制台内部绘制一个钻石,询问用户输入,然后根据输入的尺寸绘制钻石。

我无法在此处绘制钻石,因为格式无法正确显示。

我已经能够成功地让钻石的上半部分工作了,我认为下半部分很容易,因为它只是顶部的反面,但是我被困在某些东西上,我似乎无法看到弄明白。

这是我的代码:

import java.util.Scanner;

public class Diamond {

    public static void main(String[] args) {

        // import the scanner
        Scanner scanner = new Scanner(System.in);

        // Ask for the number of sides
        System.out.println("Enter the diamond size: ");
        int sides = scanner.nextInt();

        //variables for the diamond
        int matrix = sides * 2 + 3;
        int midpoint = ((matrix - 1) / 2) + 1;
        int mspaces = 0;
        int centerSpaces = 0;


        // diamond gets made here
        for (int rows = 1; rows <= midpoint; rows++) {
            int spaces = (sides * 2 + 2) - (sides + rows);
            if (rows == 1) {
                for (int x = 1; x <= spaces; x++) {
                    System.out.print(" ");
                }
                System.out.print("^\n");
            }

            //top half of the diamond
            if (rows > 1 && rows < midpoint) {

                if (rows > 2) {
                    mspaces += 2;
                }

                for (int x = 1; x <= spaces; x++) {
                    System.out.print(" ");
                }
                System.out.print("/");

                for (int k = 0; k <= mspaces; k++) {
                    System.out.print(" ");
                }

                System.out.print("\\\n");

                centerSpaces = mspaces + 2;

            }

            //center of the diamond
            if (rows == midpoint) {
                System.out.print("<");
                for (int i = 0; i <= centerSpaces; i++) {
                    System.out.print(" ");
                }
                System.out.print(">");
            }
        }

        //Bottom half of the diamond
        for (int x = midpoint - 1; x <= 1; x--) {

            int downSpace = (sides * 2 + 2) - (sides + x);

            System.out.println("\n");

            if (x == 1) {
                for (int y = 1; y <= downSpace; y++) {
                    System.out.println(" ");
                }

                if (x > 2) {
                    mspaces += 2;
                }

                for (int y = 1; x <= downSpace; y++) {
                    System.out.print(" ");
                }
                System.out.print("\\");

                for (int k = 0; k <= mspaces; k++) {
                    System.out.print(" ");
                }

                System.out.print("/\n");

                centerSpaces = mspaces + 2;

            }
        }

    }
}

如果我不得不猜测它是什么,那么钻石下半部分的if声明就会出现问题,但我并不确定。

编辑:

以下是钻石上半部分的截图:

enter image description here

1 个答案:

答案 0 :(得分:1)

循环从不运行:应该阅读x>=1(我认为)

for (int x = midpoint - 1; x <= 1; x--)

可能的无限循环:应该阅读y <= downSpace

for (int y = 1; x <= downSpace; y++)