2014-12-06 30 views
0

我很難搞清楚java賦值中的最後一個模式。我知道我很接近,但我想不出它在這裏是我的代碼:使用嵌套循環在java中製作模式

public static void main(String[]args){ 
    System.out.println("Pattern D:"); 
    for (int i = 6; i>=1; i--) { // row 
     int x = 6; // Counter? 
     for (int j = 1; j<=i; j++){ //column 
      System.out.print(""); 
      x--; 
     } 
     for(int k=1;k<=i;k++) { 
      System.out.print(x); 
     } 
     System.out.println(); 
    } 
} 

據我所知,外環是行內的列,但是這不是我有錯的部分。我自己的模式是正確的,但不是數字的輸出。 我不能把我的輸出放在這裏,因爲它不會格式正確。但是,如果你完全複製我的代碼而不是一行0,然後1,然後,2 ...等,我試圖在頂線上獲得1 2 3 4 5 6,然後1 2 3 4 5,下一行等...

回答

0

你實際上非常接近正確的模式,你只是增加了一點點。作爲一個通用的提示(並不總是,但大部分時間),在製作這些循環模式時,通常可以使用循環中的整數打印這些模式。我改變了一下你的代碼,給你你想要的模式。你不需要x作爲計數器,因爲你可以使用你最深的嵌套循環的整數作爲計數器,這在我剛剛調整你的代碼的方式是j,因爲它會在第一次運行6次,然後在第二次運行5次上。您添加的另一個額外部分是第三個嵌套循環。它基本上完成了與第二回合完全相同的事情,因爲它們都具有運行的條件,而它們比我小。那麼這裏是代碼;我希望我的解釋有幫助。

public static void main(String[]args){ 
    System.out.println("Pattern D:"); 
    for (int i = 6; i>=1; i--) { // row 
     for (int j = 1; j<=i; j++){ //column 
      System.out.print(j); 
     } System.out.println(); 
    } 
} 
+0

啊,實際上改變了格局。我想我搞砸了我的意思。我試圖得到的模式是正確的完整的通過頂部的6行。 – Kevin 2014-12-06 02:48:57

+0

是否所有的數字都需要定位在右側,還是我缺少更多? – ejmejm 2014-12-06 02:50:50

+0

老實說,我只是自己想出來的,但是是的,這是對的。我對這個糟糕的解釋表示歉意。我會發布我的解決方案 – Kevin 2014-12-06 02:58:40

0

這是您的期望代碼:

import java.util.*; 
public class Test{ 
    public static void main(String[]args){ 
     System.out.println("Pattern D:"); 
     for(int i=6 ;i >= 1;i--){ 
      int k=i; 
      for (int j=1 ;j<=k; j++){ 
       System.out.print(j); 
      } 
      System.out.println(); 
     } 

    } 
} 
0

原來我說什麼,我想提早做不對。我想爲模式辯護,但這是我的解決方案。對不起,有任何困惑。

for (i=6;i>0;i--) { 
      x=6; 
      for (j=i;j<6;j++) { 
       x--; 
       System.out.print(" "); 
      } 
      for(k=1;k<=i;k++) { 
      System.out.print(x--); 
      } 

      System.out.println(" "); 
     } 
0
public class TestPattern { 
    public static void main(String[] args) { 

     for (int i = 6; i >= 1; i--) { 
      for (int j = 1; j <= i; j++) { 
       System.out.print(j); 
      } 
      System.out.println(); 
     } 
    } 
} 

輸出:

123456 
12345 
1234 
123 
12 
1