我正在尝试在同一条线上打印一个正方形和一个三角形,如下所示:
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
我已经创建了单独制作它们的功能
public static void drawTriangle(int n) {
int k = 2 * n - 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
System.out.print(" ");
}
k = k - 1;
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
public static void drawSquare(int width, int height) {
for (int i = 0; i < height; i++) {
System.out.print("* ");
}
System.out.println();
for (int i = 0; i < width - 2; i++) {
System.out.print("* ");
for (int j = 0; j < height - 2; j++) {
System.out.print("* ");
}
System.out.println("* ");
}
for (int i = 0; i < height; i++) {
System.out.print("* ");
}
System.out.println();
}
但我不知道如何将两个输出组合在同一行上。
最佳答案
解决方案
最简单的解决方案是将这两种方法合二为一,如下所示:
public static void drawTriangleAndSquare(int widthS, int heightS) {
// number of leading spaces in front of triangle
int k = 2 * heightS - 5;
// print square
for (int i = 0; i < heightS; i++) {
for (int j = 0; j < widthS; j++) {
System.out.print("* ");
}
// print triangle
System.out.print("\t");
for (int j = 0; j < k; j++) {
System.out.print(" ");
}
k--;
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String[] args) {
drawTriangleAndSquare(5, 4);
}
输出
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
请注意,我稍微清理了您的代码,尤其是 drawSquare()
函数。
限制
我的实现只允许打印相同高度的正方形和三角形(它们都依赖于 drawTriangleAndSquare()
中的变量 heightS
)。
附言如果你想在三角形和正方形之间有更多的空白,只需在 System.out.print("\t")
中添加更多的 \t
。
关于java - 在同一行上打印形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341053/