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

xdnvmnnf  于 2021-07-06  发布在  Java
关注(0)|答案(3)|浏览(352)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

13小时前关门了。
改进这个问题
我对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 在我的代码循环,任何帮助/提示将不胜感激!谢谢您!

cigdeys3

cigdeys31#

这里有一些需要考虑的事情。
你只需要一个循环,那就是行。
可以使用 String.repeat() 方法。更简单。然后可以转换为for循环。
每行必须基于当前行缩进。
每行必须有奇数个冒号,同样基于当前行。
要控制不必要的换行符,请使用 System.print() 以及 System.println() 随便玩玩。记住这两个 2*n-1 以及 2*n+1 什么时候 n 是一个整数产生一个奇数。
仅供参考

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

相当于

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

qnakjoqk2#

你可以用 String::repeat 如果使用java 11或更高版本:

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

对于Java8,可以使用 Collections::nCopies 以及 String::join :

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

r6hnlfcb3#

目前您看到:

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

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

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();
      }
    }
}

相关问题