java实现输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字

   public static void main (String[] args) {
    /*
     * 1 2 3 4
     * 5 6 7 8
     * 9 10 11 12
     * 13 14 15 16
     *
     * 4 33 22 11
     * */
    int n =2;
    int[][] ints = new int[n][n];
    full(ints); 
    myprint(ints);
}


private static void full (int[][] ints) {
    int x =1;
    for (int i = 0; i < ints.length; i++) {
        for (int i1 = 0; i1 < ints[i].length; i1++) {
            ints[i][i1] = x++;
        }
    }

}

private static void myprint (int[][] ints) {
    //获取数组的列数
    int col = ints[0].length;

    //获取行数
    int row = ints.length;
    int x = 0;
    int y = 0;
    System.out.println(ints[x][y]);
    for (int i = 0; i < (col + 1) / 2; i++) {

        //从左向右遍历
        for (int i1 = y; i1 < col - i -1; i1++) {
            System.out.println(ints[x][++y]);
        }
        //从上到下遍历
        for (int i1 = x; i1 < row - i -1; i1++) {
            System.out.println(ints[++x][y]);
        }
        //从右到左遍历
        for (int i1 = y; i1 > i ; i1--) {
            System.out.println(ints[x][--y]);
        }
        //从下向上
        for (int i1 = x; i1 > i+1; i1--) {
            System.out.println(ints[--x][y]);
        }
    }
}

你可能感兴趣的:(代码)