使用星号创建沙漏

我想用“*”字符创建一个沙漏。 例如,如果用户输入为5,那么它将如下所示:

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

和3看起来像这样:

  *** * *** 

到目前为止我有:

 public static void draw(int W){ stars(W); if (W > 1) { draw(W-1); stars(W); } } public static void stars(int n){ System.out.print("*"); if(n>1) stars(n-1); else System.out.println(); } 

它创造了

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

Java中的完整解决方案

 public static void draw(int w){ draw(w, 0); } public static void draw(int W, int s){ stars(W, s); if (W > 2) { draw(W-2, s+1); stars(W, s); } } public static void stars(int n, int s){ if(s > 0){ System.out.print(" "); stars(n, s-1); } else if (n > 0){ System.out.print("*"); stars(n-1, s); } else { System.out.println(); } } 

引入参数s是为了跟踪中心星号所需的空格数量。另一种方法是使用一些全局参数来跟踪总宽度并进行减法,但你似乎真的喜欢递归。

这段代码

 for(int i = 1; i < 7; i++){ System.out.println("An hourglass of width " + i); draw(i); System.out.println(); } 

现在输出这个

 An hourglass of width 1 * An hourglass of width 2 ** An hourglass of width 3 *** * *** An hourglass of width 4 **** ** **** An hourglass of width 5 ***** *** * *** ***** An hourglass of width 6 ****** **** ** **** ****** 

伪代码:

 function stars(n): c1 = 0 c2 = n for i = 1 to n print ' ' * c1 print '*' * c2 if (i < (n+1) / 2): c1 ++; c2 -=2; else: c1-- c2 +=2 print newline 

这应该让你接近你的答案......现在转换成java

**注意 - 这适用于奇数。 您可能需要调整甚至n **