使用for循环在Java中形成一个金字塔图形



我对Java还很陌生,我必须使用for循环来形成这个图形:

/:
/:::
/:::::
/:::::::
/:::::::::

这是我的代码:

for (int row = 1; row <= 5; row++)
{
for (int column = 1; column <= row; column++)
{
System.out.print(" ");
}
for (int column = 1; column < row; column++)
{
System.out.print("/");
}
for (int column = 1; column < row; column++)
{
System.out.print(":");
}
for (int column = 1; column < row; column++)
{
System.out.print("\");
}
System.out.println();
}

我的代码生成下图:

/:
//::\
///:::\
////::::\\

我不知道如何在我的代码中固定间距和减少for循环的数量,任何帮助/提示都将不胜感激!非常感谢。

当前您看到的是:

/:
//::\
///:::\
////::::\\

要固定间距,请将第一个循环更改为:

for (int column = 1; column <= 5-row; column++)
{
System.out.print(" ");
}

要获得正确的冒号数量,请注意,我们想要一个函数,它意味着整数到奇数,其中一个函数是f(n(=2n+1,使用1-索引,我们可以使用f(n(=2n来修复它。您也不需要在循环中打印侧面。

总的来说,你应该得到这样的东西:

public class Main
{
public static void main(String[] args) {
for (int row = 1; row <= 5; row++)
{
for (int column = 1; column <= 5-row; column++)
{
System.out.print(" ");
}
System.out.print("/");
for (int column = 1; column < 2*row; column++)
{
System.out.print(":");
}
System.out.print("\");
System.out.println();
}
}
}

以下是一些需要考虑的事项。

  • 您只需要一个循环,那就是行
  • 可以使用CCD_ 2方法来创建每一行。这更容易。然后可以转换到for循环
  • 每一行都必须根据当前行缩进
  • 每一行必须有奇数个冒号,同样以当前行为基础

要控制不必要的换行,请使用System.print()System.println()的组合

记住,当n是整数时,2*n-12*n+1都会产生奇数。

FYI

System.out.print(":".repeat(n));

相当于

for(int i = 0; i < n; i++) {
System.out.print(":");
}

如果使用Java 11或更高版本,则可能使用String::repeat

for (int i = 0; i < 5; i++) {
System.out.println(" ".repeat((4 - i)) + "/" + ":".repeat(i * 2 + 1) + "\");
}

对于Java 8,可以使用Collections::nCopiesString::join:

for (int i = 0; i < 5; i++) {
System.out.printf("%" + (5 - i) + "s%s\%n", "/", String.join("", Collections.nCopies(2 * i + 1, ":")));
}

最新更新