2014-11-04 86 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