java - 在Java中打印*的金字塔
问题描述
我想知道你能不能帮帮我。我正在尝试在 java 中编写一个嵌套的 for 循环,它显示一个数字金字塔三角形,看起来像
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
这是我到目前为止所拥有的:
class Triagle {
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String[] args) {
printTriagle(12);//I want to set the triangle to be height of 12
}
}
我的结果不等于预期的输出:
___________*#
__________*_*#
_________*_*_*#
________*_*_*_*#
_______*_*_*_*_*#
______*_*_*_*_*_*#
_____*_*_*_*_*_*_*#
____*_*_*_*_*_*_*_*#
___*_*_*_*_*_*_*_*_*#
__*_*_*_*_*_*_*_*_*_*#
_*_*_*_*_*_*_*_*_*_*_*#
*_*_*_*_*_*_*_*_*_*_*_*#
解决方案
我已经更新了您的代码并添加了注释,以便您理解。参考下面的代码:
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print("_");
}
String s = "_";
if (i + 1 >= n) // check if it is the last line
s = "*"; // change to print * instead of _
for (int j = 0; j <= i; j++) {
// printing stars
if (j == i)
System.out.print("*#"); // check if the last print of the line
else if (j == 0)
System.out.print("*" + s); // check if the first print of the line
else
System.out.print(s + s);
}
System.out.println();
}
}
结果:
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
推荐阅读
- excel - 以波浪号分隔的导出
- flask - 烧瓶将shapefile上传到postgis
- javascript - jQuery if 语句在 for 循环中不起作用
- java - iText,加载现有的 PDF 并向其中添加文本
- python - github 上的一些要点有很多分支。我怎样才能找到最近活跃的和/或大量修改的?
- scala - scala计算元素的出现次数
- javascript - 空间复杂度js函数
- java - 我如何使用 JQuery 要求和打印一个对象数组 beetwen 一个 jsp 页面和一个 servlet?
- regex - 两个字符串之间的正则表达式,不包括字符串
- macos - 如何对行中没有“@”字符的所有行进行 grep