java - 我怎样才能在java中修复这个星星金字塔
问题描述
我必须通过用户输入打印星星的金字塔,用户输入:多少行,多少列。我盯着一颗星,每次迭代将星数增加 2,将行数减少 1。我无法确定我必须做多少空间。
我必须做什么:示例:
printStars(4,2) rows = 4 , columns = 2.
output :
* *
*** ***
***** *****
******* *******
printStars(3,3) rows= 3 , columns =3.
output :
* * *
*** *** ***
***** ***** *****
printStars(3,4) rows = 3 , columns =4.
output:
* * * *
*** *** *** ***
***** ***** ***** *****
编码:
private static void printStars(int rows, int columns ) {
int stars = 1;
while (rows > 0) {
int spaces = rows;
for (int i = 1; i <= columns; i++) {
for (int sp = spaces; sp >=1; sp--) {
System.out.print(" ");
}
for (int st = stars; st >= 1; st--) {
System.out.print("*");
}
}
System.out.println();
stars += 2;
rows--;
}
}
我得到了什么:
printStars(3,4)
output:
* * * *
*** *** *** ***
***** ***** ***** *****
解决方案
乍一看,您似乎没有考虑打印星星后出现的空间。尝试像这样修改代码:
private static void printStars(int rows, int columns)
{
int stars = 1;
while (rows > 0) {
int spaces = rows;
for (int i = 1; i <= columns; i++) {
for (int sp = spaces; sp >= 1; sp--) {
System.out.print(" ");
}
for (int st = stars; st >= 1; st--) {
System.out.print("*");
}
for (int sp = spaces; sp >= 1; sp--) {
System.out.print(" ");
}
}
System.out.println();
stars += 2;
rows--;
}
}
推荐阅读
- c# - 将 FK 约束异常与 EF Core 中的其他数据库异常区分开来?
- twitter-bootstrap - 多项目轮播的响应性问题(已解决)
- javascript - 创建一个支持函数的持久数据钩子
- vbscript - Adobe Illustrator 脚本
- c# - 如何根据其他 2 个属性的值设置 1 个属性的值?
- testing - jest.mock 和 jest.doMock 之间的区别
- scala - 在 uber jar 而不是单个子模块 jar 中构建 sbt 项目
- java - 使用 Volley android studio 发布 JSONObject 时出错
- java - 为什么Generetemap没有显示?
- python - 如何在没有基类的情况下混入 Python 类?