2016-11-04 70 views
-1

所以我想做一个代码,其中的输出如下:Java的三角形使用星

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

通过输入4.价值因此,基本上,7星和第一线没有空格,5第二行前面的星星和1个空间等等。

我认为这是正确的,但它没有给我输出,我想?

public static void Stars(int a) 
    { 
     String newStars = ""; 
     String stars = "", spaces = ""; 
     for (int i = 1; i <= a; i++) 
     { 
      for (int j = 2*a - 1; j > 0; j--) 
      { 
       stars += "*"; 
      } 
      for (int k = 0; k < a; k++) 
      { 
       spaces += " "; 
      } 
      newStars = spaces + stars; 
      System.out.println(newStars); 
     } 
    } 

它没有给出正确的输出,但我不知道什么是错我的代码...

+0

你询问它是否给出正确的输出?你不知道吗? –

+0

不,我是问我的代码有什么问题 – user7112926

+0

1)你应该在循环内初始化'stars'和'spaces' *(在开始处)。 --- 2)你的内部循环应该使用'i'的值,因为它们需要根据生成的行来执行不同数量的字符。 – Andreas

回答

0

spacesstars必须在外环内进行初始化。

+0

只有部分答案。 – Andreas

0

下面是一些代码,让你去:

public static void Stars(int a) { 
    int starsc = 0, spacesc = 0; 
    for (int i = (2 * a - 1); i > 0; i = i - 2) { // i - 2 decreases stars by 2 
     starsc = i; 
     if (i != (2 * a - 1)) { // if this is the first line, no spaces! 
      spacesc = (2 * a - 1) - i; 
     } 
     System.out.println("stars count: " + starsc + " spaces count: " + spacesc); 
    } 
} 

我们计算应该在每行打印的明星和空间的数量,继续和格式...