簡體   English   中英

打印ASCII菱形:底部一半破了?

[英]Printing an ASCII Diamond: Bottom half broken?

我試圖使用用戶輸入的寬度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循環很棘手

嘗試將循環的下半部分中的3更改為4。看來您缺少一行。 那可能會做到。 無法保證我是新來的,只是想幫忙! :)

為了簡單修復,將底部循環變量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');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM