2014-11-04 89 views
0

嗨所以我工作的一個問題,我需要打印使用循環打印模式

1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
public class Set_5_P5_18b { 

    public static void main(String[] args) { 
     int x; 
     String y; 
     x = 1; 
     y = ""; 

     System.out.println("Pattern B:"); 
     while (x < 7) { 
      y = y + x + " "; 
       x++; 
     } 
     System.out.println(y); 

    } 

} 

我寫上面打印有什麼第一線,但我無法弄清楚如何修改它打印第二個,有人可以幫我嗎?

+7

你嘗試過什麼?你需要另一個循環。請注意,SO不是調試器。 – 2014-11-04 17:43:06

+0

第二行在哪裏? – eduyayo 2014-11-04 17:44:05

+0

從n = 6開始,將i = 0打印到n,並且每步減少n ... – 2014-11-04 17:44:25

回答

1

尤其需要外部for循環來運行,比如說x的值從6到1.對於x的每個值,您需要一個內部循環,運行值爲1 ... x並在一行中輸出值。

記住這一點,並嘗試首先提出僞代碼,然後再實現代碼。

0

你的輸出可以像的2維陣列,其中可以觀察到:

  • 索引i生長頂部至底部,並且表示行索引
  • 索引j生長左到右,表示列索引

enter image description here

你現在正在做的權迭代的列第一行就是這樣。 正如在評論中提到的,你應該添加第二個循環遍歷行。

這裏是你如何可以用兩個for循環實現這一目標:

int colSize = 6; 
int rowSize = 6; 
for(int i = 1; i <= rowSize; i++) { 
    for(int j = 1; j <= colSize; j++) { 
     System.out.print(j + " ");  // print individual column values 
    } 
    System.out.println();    // print new line for the next row 
    colSize--;       // decrement column size since column size decreases after each row 
} 
0

你必須重新設置變量x,當你退出時:P

0

如此普遍,當你寫一個for循環,並且您意識到您希望for循環的某個方面在每次迭代時發生更改,而您希望使用嵌套for循環的9/10次(for for循環內的for循環)。

因此,基本上每次迭代for循環時,都希望for循環的持續時間減少。所以......

for (int num =1; num < <number that you want to change>; num++) {}

下面是代碼的方法。

public static void print(int x) { 
    for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) { 
     for (int num = 1; num <= lengthOfFor; num++) { 
      System.out.print(num + " "); 
     } 
     System.out.print("\n"); 
    } 
} 

這就是你將如何調用該方法。

public class print 
{ 
    public static void print(int x) { 
     for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) { 
      for (int num = 1; num <= lengthOfFor; num++) { 
       System.out.print(num + " "); 
      } 
      System.out.print("\n"); 
     } 
    } 
    public static void main (String[] args) { 
     print(6); 
    } 
} 
0

解決方案:

public static void printPattern(int rows) { 
    IntStream.range(0, rows).map(r -> rows - r).forEach(x -> { 
     IntStream.rangeClosed(1, x).forEach(y -> { 
      System.out.print(String.format("%3d", y)); 
     }); 
     System.out.println(); 
    }); 
} 

用法:

printPattern(9); 

輸出:

1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1