我试图在设置行数和梯形底边宽度后输出一个梯形。目前,它在某些情况下有效,但在其他情况下无效。
在这个例子中,它有效
Enter height: 5
Enter width: 16
@@@@@@@@
@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
在这一个中,它没有
Enter height: 5
Enter width: 14
@@@@@@@
@@@@@@@@@
@@@@@@@@@@@
@@@@@@@@@@@@@
@@@@@@@@@@@@@@@
我做错了什么?这是我的代码:
public void printTrapezoid(Scanner sc)
{
int width;
int rows;
System.out.print("Enter height: ");
rows = sc.nextInt();
System.out.print("Enter width: ");
width = sc.nextInt();
System.out.println("");
for (int i = 0; i < rows; i++)
{
for (int j = rows - i; j > 0; j--)
{
System.out.print(" ");
}
for (int j = 0; j < (width / 2) + (2 * i); j++)
{
System.out.print("@");
}
System.out.print("\n");
}
System.out.println("");
}
最佳答案
我会保持简单:您希望在基数之前为每行删除两个 block ,因此我可能会从 rows - 1
到 0
(含)计算 i
:
for (int i = rows - 1; i >= 0; --i)
并在循环中为每个i
减去两个 block :
int blocks = width - i * 2;
由于我们只需要在每行打印一个空格(而不是两个,暗示尾随空格),并且由于我们向后计数 i
,因此我们只输出 i
空格。
所以:
public void printTrapezoid(Scanner sc)
{
int width;
int rows;
System.out.print("Enter height: ");
rows = sc.nextInt();
System.out.print("Enter width: ");
width = sc.nextInt();
System.out.println();
for (int i = rows - 1; i >= 0; --i)
{
int blocks = width - i * 2;
for (int j = 0; j < i; ++j)
{
System.out.print(" ");
}
for (int j = 0; j < blocks; ++j)
{
System.out.print("@");
}
System.out.println();
}
System.out.println("");
}
对于 5/14 输出以下内容:
@@@@@@ @@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@
这是 5/16:
@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@
关于java - 在Java中打印梯形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43195858/