所以我试图创建一个输出看起来像的代码:
*******
*****
***
*
输入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)
spaces
和stars
。
答案 1 :(得分: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);
}
}
我们计算每行应打印的星星和空格的数量,然后格式化......