Java 打印回形二维数组

print(6, 7);

private void print(int x, int y) {
    int index = 0;
    int line = 0;
    //0右,1下,2左,3    int direction = 0;
    int x2 = x;
    int y2 = y;

    String[][] arr = new String[x][y];
    for (int i = 0, size = x * y; i < size; i++) {
        if (i < 10) {
            arr[index][line] = "0" + i + "";
        } else {
            arr[index][line] = i + "";
        }
        if (direction == 0) {
            if (index == x2 - 1) {
                direction++;
            } else {
                index++;
            }
        }
        if (direction == 1) {
            if (line == y2 - 1) {
                direction++;
            } else {
                line++;
            }
        }
        if (direction == 2) {
            if (index == x - x2) {
                direction++;
                y2--;
            } else {
                index--;
            }
        }
        if (direction == 3) {
            if (line == y - y2) {
                direction = 0;
                x2--;
                index++;
            } else {
                line--;
            }
        }

    }

    String print = "";
    for (int j = 0; j < y; j++) {
        for (int i = 0; i < x; i++) {
            print = print + arr[i][j] + " ";
        }
        print = print + "\n";
    }

    System.out.print(print);
}

04-19 18:11:36.435 22811-22811/com.untek.mes.tdpad I/System.out: 00 01 02 03 04 05 
04-19 18:11:36.435 22811-22811/com.untek.mes.tdpad I/System.out: 21 22 23 24 25 06 
04-19 18:11:36.435 22811-22811/com.untek.mes.tdpad I/System.out: 20 35 36 37 26 07 
04-19 18:11:36.435 22811-22811/com.untek.mes.tdpad I/System.out: 19 34 41 38 27 08 
04-19 18:11:36.435 22811-22811/com.untek.mes.tdpad I/System.out: 18 33 40 39 28 09 
04-19 18:11:36.435 22811-22811/com.untek.mes.tdpad I/System.out: 17 32 31 30 29 10 
04-19 18:11:36.435 22811-22811/com.untek.mes.tdpad I/System.out: 16 15 14 13 12 11 



猜你喜欢

转载自blog.csdn.net/shu_quan/article/details/80008836