打印ax,y矩阵,java

我想使用for循环打印followin矩阵:

1 2 3 4 5 6 2 3 4 5 6 1 3 4 5 6 1 2 4 5 6 1 2 3 5 6 1 2 3 4 6 1 2 3 4 5 

我用:

 public static void main ( String [ ] args ) { for(int w = 1; w <= 6; w++){ System.out.println(""); for(int p = w; p <= 6; p++){ System.out.print(p + ""); } } } 

但它打印:

  1 2 3 4 5 6 2 3 4 5 6 3 4 5 6 4 5 6 5 6 6 

将内循环更改为:

 for (int p = w; p <= 6 + w; p++) { System.out.print((p - 1) % 6 + 1 + " "); } 

我认为使用modulo打印每种可能的组合更容易。 但是,这会返回0到5之间的数字,因此您必须添加1。

 final int SIZE = 6; for(int w = 0; w < SIZE; w++) { for(int p = 0; p < SIZE; p++) { System.out.print(((w + p) % SIZE) + 1); System.out.print(" "); } System.out.println(); } 
 public static void main ( String [ ] args ) { for(int w = 0; w < 6; w++){ System.out.println(""); for(int p = 0; p < 6; p++){ System.out.print((p + w) % 6 + 1 + ""); } } } 

这应该可以帮到你。 几乎你要做什么,但有一个额外的for循环。

 public static void main(String[] args) { for (int w = 1; w <= 6; w++) { System.out.println(""); for (int p = w; p <= 6; p++) { System.out.print(p + ""); } for (int q = 1; q < w; q++) { System.out.print(q + ""); } } } 

虽然我没有测试过,但这会有效!:

 for(int w = 1; w <= 6; w++){ System.out.println(""); for(int p = 0; p <= 5; p++){ if((w+p) <=6) { System.out.print((w+p) + ""); } else { System.out.print((w+p-6) + ""); } } } 

干杯

这种情况正在发生,因为你的内循环取决于w,但是w正在递增。

编辑 – 这是我想出的

 public class Loop { public static void main(String[] args) { for (int w = 1; w <= 6; w++) { System.out.println(""); Loop.printRow(w); } } public static void printRow(int startAt) { int p = startAt; for(int i = 0; i <= 6; i++, p++){ if (p > 6) p -= 6; System.out.print(p + ""); } } } 

其他人用modulo给出了花哨的解决方案,但我认为最简单的方法是让第二个内环覆盖第一个内环错过的数字。

 public static void main ( String [ ] args ) { for(int w = 1; w <= 6; w++){ for(int p = w; p <= 6; p++){ System.out.print(p + ""); } for(int p = 1; p < w; p++){ System.out.print(p + ""); } System.out.println(""); } }