我無法理解嵌套循環和數字模式是如何工作的。我已經完成了除3之外的所有模式。有人可以幫助我使用這段代碼並解釋它是如何工作的嗎?有人可以解釋Java嵌套循環如何處理數字模式嗎?
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
能有人幫和向我解釋如何呢?
**調試器:**「我可以解釋!!」 – Maroun
問題很少。這是你的功課嗎? – user1555863
@Maroun Maroun好的。我究竟做錯了什麼? –