如何镜像一个不超过四个沙漏的沙漏?

时间:2018-04-17 08:22:02

标签: java loops for-loop hourglass

我想知道如何镜像一个半沙漏......不超过4个循环。我不想使用递归或数组,只是简单的循环

    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter odd number above 0 here: ");
    int h = sc.nextInt();
    char x = '#';

    if (h % 2 != 0) {
        for (int i = 1; i <= h; i++) {

            // loop for first part of hourglass
            for (int j = 1; j <= i; j++) {
                System.out.print(x);
            }
            // create white space
            for (int j = h - i; j >= 1; j--) {
                System.out.print("  ");
            }
            // create mirror
            for (int k = i; k >= 1; k--) {
                System.out.print(x);
            }

            System.out.println();
        }

    } else {
        System.out.println(" Not an odd number. Try again: ");
    }

3 个答案:

答案 0 :(得分:1)

在String []数组中构建前半部分,然后正常打印然后向后打印。你也可以为垂直对称做到这一点。

答案 1 :(得分:1)

您可以在一个for循环中执行此操作并实际删除所有嵌套的for循环,请尝试以下操作:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter odd number above 0 here: ");
    int h = sc.nextInt();
    String x = "#";

    if (h % 2 != 0) {
        for (int i = 1; i <= h; i++) {
            String hash = new String(new char[i]).replace("\0", x);
            System.out.print(hash);
            String spaces = new String(new char[2*(h-i)]).replace("\0", " ");
            System.out.print(spaces);
            System.out.print(hash);

            System.out.println();
        }

    } else {
        System.out.println(" Not an odd number. Try again: ");
    }
}

不确定它是你在找什么,但它们最终会有相同的结果。 我已将xchar更改为String以及replace功能。如果您希望将x保留为char,则可以在String.valueOf(x)中执行replace()

答案 2 :(得分:0)

您可以简单地执行相同的for loop,只需在迭代器中进行简单的更改:

    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter odd number above 0 here: ");
    int h = sc.nextInt();
    char x = '#';

    if (h % 2 != 0) {
        for (int i = 1; i < 2*h; i++) {

            int a = Math.abs(h-i);
            // loop for first part of hourglass
            for (int j = a; j < h; j++) {
                System.out.print(x);
            }
            // create white space
            for (int j = 0; j <a; j++) {
                System.out.print("  ");
            }
            for (int j = a; j < h; j++) {
                System.out.print(x);
            }

            System.out.println();
        }
    } else {
        System.out.println(" Not an odd number. Try again: ");
    }