2017-04-21 189 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(); 
    }); 
}