使用for循环在Java中形成金字塔图形
我对Java相当陌生,我必须使用for循环来形成这个图:使用for循环在Java中形成金字塔图形,java,Java,我对Java相当陌生,我必须使用for循环来形成这个图: /:\ /:::\ /:::::\ /:::::::\ /:::::::::\ 这是我的密码: for (int row = 1; row <= 5; row++) { for (int column = 1; column <= row; column++) { System.out.print(" "
/:\
/:::\
/:::::\
/:::::::\
/:::::::::\
这是我的密码:
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循环String.repeat()
- 每行必须基于当前行缩进
- 每行必须有奇数个冒号,同样基于当前行
System.print()
和System.println()
随便玩玩吧。请记住,当n
为整数时,2*n-1
和2*n+1
都会产生奇数
供参考
相当于
for(int i = 0; i < n; i++) {
System.out.print(":");
}
for(int i=0;i
目前,您可以看到:
/:\
//::\\
///:::\\\
////::::\\\\
要固定间距,请将第一个循环更改为:
for(int column=1;column如果使用Java 11或更高版本,则可以使用String::repeat
:
for(int i=0;i<5;i++){
System.out.println(“.repeat((4-i))+”/“+”:“.repeat(i*2+1)+“\\”);
}
对于Java 8,可以使用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,:”)));
}
你的代码到底出了什么问题?你应该把它看作一个网格,所以你基本上需要两个for循环,而不是5。你的维度是什么?@Alex你双重评论。你所说的维度是什么意思?>我必须用for循环来形成这个数字。这是为了一个类,如果是这样的话,那么我可能付出太多了哈哈
for(int i = 0; i < n; i++) {
System.out.print(":");
}
/:\
//::\\
///:::\\\
////::::\\\\
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();
}
}
}