java - 在同一行上打印形状
问题描述
我正在尝试在同一行上打印一个正方形和一个三角形,如下所示:
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
我已经创建了单独制作它们的功能
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()
函数。
局限性
我的实现只允许您打印相同高度的正方形和三角形(它们都依赖于 中的变量heightS
)drawTriangleAndSquare()
。
PS如果你想在三角形和正方形之间有更多的空白,只需添加更多\t
的 s at System.out.print("\t")
。
推荐阅读
- openshift - 了解inf openshift源码策略
- javascript - 如何在 HTML 中创建一个轮播,并在左侧/右侧显示上一个/下一个图像?
- oracle - 在 ref_cursor 中返回该查询之前,如何将查询的行数放入变量中?
- python - 熊猫将列表值从一列应用到另一列
- javascript - Node JS随机改变输出
- android - android项目可以使用子模块的依赖吗?
- python - 'DataFrame' 对象没有属性 'concat'
- android - 如何在 Android Studio 中获取当前日期?
- electron - 如何使用 Electron 启用离线 PWA 应用程序?
- ruby-on-rails - 将 has_secure_token 与 rails 中的现有记录一起使用