2017-04-21 115 views
-1

我的目標是當輸入爲3得到這個輸出:如何使用for循環在Java中打印x模式?

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

這裏是我的代碼:

public static void PrintX (int number) { 
for (int i = 0; i <= (number * 2 + 1); i++) 
    { 
     for (int j = 0; j <= (number * 2 + 1); j++) 
     { 
      if (i == j) 
      { 
       System.out.print("*"); 
      } 
      else if (i + j == (number * 2 + 2)) 
      { 
       System.out.print("*"); 
      } 
      else 
      { 
       System.out.print(" "); 
      } 
     } 
     System.out.println(""); 
    } 
} 

我的輸出輸入時爲3就是這個樣子,我不知道爲什麼會出現是頂級的額外明星。

* 
*  * 
    * * 
    * * 
    * 
    * * 
    * * 
*  * 
+5

走。考慮當i = 0和j = 0時會發生什麼。 –

回答

-2

設置i = 1內部for循環。編譯並運行下面的例子:如您所願,如果你設置的1初始i

public class TestPrintX { 
     public static void PrintX (int number) { 
     for (int i = 1; i <= (number * 2 + 1); i++) 
      { 
       for (int j = 0; j <= (number * 2 + 1); j++) 
       { 
        if (i == j) 
        { 
         System.out.print("*"); 
        } 
        else if (i + j == (number * 2 + 2)) 
        { 
         System.out.print("*"); 
        } 
        else 
        { 
         System.out.print(" "); 
        } 
       } 
       System.out.println(""); 
      } 
     } 
     public static void main(String arg[]) { 
      PrintX(3); 
     } // end of main method 
} // end of class 
+4

你會提供任何解釋什麼是錯的,你改變了什麼? – csmckelvey

+0

謝謝,這是有道理的。 int i = 1而不是int i = 0 – Deryck

+0

@mo sean,不要強制OP接受,不應該在這裏。 –

1

你的外環會工作。不過,你也可以縮短這個時間。首先,考慮存儲number * 2 + 1。然後你可以將幾個lambda表達式與IntStream結合起來。基本上,你要每個可能的索引來" ""*"地圖 - 通過手或調試代碼,以便

public static void PrintX(int number) { 
    int len = number * 2 + 1; 
    IntStream.rangeClosed(1, len).forEachOrdered(i -> { 
     IntStream.rangeClosed(0, len) 
       .mapToObj(j -> i == j || i + j == len + 1 ? "*" : " ") 
       .forEachOrdered(System.out::print); 
     System.out.println(); 
    }); 
}