gpt4 book ai didi

java - Java中使用for循环的等边三角形

转载 作者:太空宇宙 更新时间:2023-11-04 13:51:59 24 4
gpt4 key购买 nike

我正在尝试绘制一个由星号字符组成的等边三角形,但是当用户输入行号时,该行将被绘制为 "x" 并且整个三角形将是 "*" 但我在空格中出现错误。

这是我的代码:

int number_of_stars = getHeight();
for (int rows=1; rows <= getHeight(); rows++)
{
for (int spaces=1; spaces <= number_of_stars; spaces++)
{
System.out.print(" ");
}

if(rows == getRowNum()){
for (int star=1; star <= rows; star++)
{
System.out.print("x");
System.out.print(" ");
}
System.out.println("");
rows = getRowNum()+1;
System.out.print(" ");
System.out.print(" ");
System.out.print(" ");

}
for (int star=1; star <= rows; star++)
{
System.out.print("*");
System.out.print(" ");
}
System.out.println("");
number_of_stars = number_of_stars - 1;
}

输出为

      * 
* *
* * *
* * * *
* * * * *
* * * * * *
x x x x x x x
<小时/>
 * * * * * * * * * 
* * * * * * * * * *

第九行和第十行不正确

最佳答案

IMO 您想要对特定行号进行的唯一更改是打印 x 而不是 *,为此您只需更改要打印的字符即可。我尝试了这个示例代码:

public static void main(String[] args) {
int userRowNumber = 5;
int height = 10;
int number_of_stars = height;
String charToPrint;
for (int rows=1; rows <= height; rows++)
{
charToPrint = "*";
if(rows == userRowNumber){
charToPrint = "x";
}
for (int spaces=1; spaces <= number_of_stars; spaces++)
{
System.out.print(" ");
}
for (int star=1; star <= rows; star++)
{
System.out.print(charToPrint);
System.out.print(" ");
}
System.out.println("");
number_of_stars = number_of_stars - 1;
}
}

打印出预期的内容。对于您代码中的问题,我鼓励您自己调试并找出它。

关于java - Java中使用for循环的等边三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com