打印ASCII Diamond:下半部分坏了吗?

时间:2016-11-03 03:14:24

标签: java

我正在尝试使用用户输入的宽度为7来打印钻石,该宽度应该如下所示:

    *
   * *
  *   *
 *     *
  *   *
   * *
    *

但不幸的是,我的钻石在底部搞砸了,看起来像这样:

    *
   * *
  *   *
 *     *
  *   *
    *

这是我的代码:

    public static void main (String[] args)
{
    int width = 0;
    System.out.println("What is the width?");
    Scanner keyboard = new Scanner (System.in);
    width = keyboard.nextInt();

    //Print top half of the diamond
    for (int i = 0; i < width; i += 2) {
        if (i == 0) {
            for (int j = 0; j < (width / 2) + 1; j++)
                System.out.print(' ');
            System.out.print('*');
        } else {
            for (int j = 0; j < width - i; j += 2) {
                System.out.print(' ');
            }
            System.out.print('*');
            for (int j = 0; j < i - 1; j++) {
                System.out.print(' ');
            }
            System.out.print('*');
        }
        System.out.print('\n');
    }
    //Print bottom half of the diamond
    for (int i = 0; i < 3; i+=2) {
        if (i == 2) {
            for (int j = 0; j < (width / 2) + 1; j++)
                System.out.print(' ');
            System.out.print('*');
        } else {
            for (int j = 0; j <= i + 2; j += 2) {
                System.out.print(' ');
            } System.out.print ('*');
            for (int j = 0; j < (width / 2) - i; j++) {
                System.out.print(' ');
            } System.out.print('*');
        }
        System.out.print('\n');
    }
}

我不完全确定如何修复它的底部,这就是我一直想弄清楚的!这些嵌套的for循环很棘手

2 个答案:

答案 0 :(得分:0)

尝试将下半部分中的3更改为4循环。似乎缺少一行。那可能会这样做。不能保证我是新来的,只是想帮忙! :)

答案 1 :(得分:0)

对于简单修复,请将底部循环变量i3更改为5,并在i之后从2更改为4

//Print bottom half of the diamond
for (int i = 0; i < 5; i+=2) {
    if (i == 4) {
        for (int j = 0; j < (width / 2) + 1; j++)
            System.out.print(' ');
        System.out.print('*');
    } else {
        for (int j = 0; j <= i + 2; j += 2) {
            System.out.print(' ');
        } System.out.print ('*');
        for (int j = 0; j < (width / 2) - i; j++) {
            System.out.print(' ');
        } System.out.print('*');
    }
    System.out.print('\n');
}