我无法理解嵌套循环和数字模式的工作原理。我已经完成了除 3 之外的所有模式。有人可以帮我处理这段代码并解释它是如何工作的吗?
public class Patterns7{
public Patterns7() {
}
public void displayPatternI(int lines)
{
System.out.println("\n\tPattern I\n");
for (int i = 1; i <= lines; i++)
{
for (int j = 1; j <= i; j++)
System.out.print (j + " " );
System.out.println();
}
}
public void displayPatternII (int lines)
{
System.out.println("\n\tPattern II to be implemented\n");
for (int i = 1;i <= lines; i++)
{
for(int j = i;j >= 1; j--)
System.out.print(j);
System.out.println();
}
System.out.println();
}
public void displayPatternIII (int lines)
{
System.out.println("\n\tPattern III to be implemented\n");
for (int i = 1; i <= lines; i++)
{
for (int space = 1; space <= lines-i; space++)
System.out.print (" ");
for (int j = 1; j <= i; j++)
System.out.print (j + " ");
System.out.println();
}
System.out.println();
}
}
模式 III 应该是这样的:
6
56
456
3456
23456
123456
但我能做的就是:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
我不确定如何让输出从 6 开始,然后减少然后增加。
模式 V 应该如下所示:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
但结果是这样的:
1
1 2 3
1 2 3 4 5
代码:
public void displayPatternVI (int lines)
{
System.out.println("\n\tMy Own Pattern to be implemented\n");
for (int i = 1; i <= lines/2; i++)
{
for (int space = 1; space <= (lines/2)-i; space++)
System.out.print (" ");
for (int j = 1; j <= (i*2)-1; j++)
System.out.print (j + " ");
System.out.println();
}
for (int i = 1; i <= lines/2; i++)
{
for (int space = 1; space <= i-1; space++)
System.out.print (" ");
for (int j = 1; j <= lines-(i*2)+1; j++)
System.out.print (j + " ");
System.out.println();
}
System.out.println();
}
模式 VI 应该如下所示:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
6 5 4 3 2 1 2 3 4 5 6
5 4 3 2 1 2 3 4 5
4 3 2 1 2 3 4
3 2 1 2 3
2 1 2
1
但它看起来像这样:
1
1 2 3
1 2 3 4 5
1 2 3 4 5
1 2 3
1
有人可以帮我解释一下吗?