printM
来源:互联网 发布:韩国人觉得中国人知乎 编辑:程序博客网 时间:2024/06/06 13:25
用二维数组打印出M型阵列
package array;public class Demo1 {public static String printM(int num) {int hight = num/4 +1;int x = hight -1;int y = 0;int[][] ints = new int[hight][num];boolean order = false;for(int i=1; i<=num; i++) {if(x < 0) {x = x + 2;order = true;}if(x > hight -1) {x = x - 2;order = false;} ints[x][y] = i;y++;if(order) {x++;} else {x--;} }StringBuffer sb = new StringBuffer();for(int i=0; i<ints.length; i++) {for(int j=0; j<ints[i].length; j++) {if(ints[i][j] == 0) {sb.append(" ");} else {//假设num<100if(ints[i][j]<10) {sb.append(ints[i][j]).append(" ");} else {sb.append(ints[i][j]);}}}sb.append("\r\n");}return sb.toString();}public static void main(String[] args) {System.out.println(Demo1.printM(33));}}
//output 9 25 8 10 24 26 7 11 23 27 6 12 22 28 5 13 21 29 4 14 20 30 3 15 19 31 2 16 18 32 1 17 33
0 0