首页 > 解决方案 > 使用嵌套的 for 循环修改二维数组

问题描述

我正在尝试打印出二维数组 (a) 的“中间”。例如,对于我的代码中的给定数组,我想打印:

[3,4,5,6]
[4,5,6,7]

但是我只能打印出“中间”值。我想修改方法 inner 中的二维数组 (a)并将其打印在 main 中,而不是在嵌套的 for 循环中使用 System.out.println 。我该怎么做呢?

这是我的代码:

public static int[][] inner(int[][] a) {
    int rowL = a.length - 1;
    int colL = a[1].length - 1;

    for (int row = 1; row < rowL; row++) {
        for (int col = 1; col < colL; col++) {
            //System.out.print(a[row][col]);
            a = new int[row][col];
        }
        System.out.println();
    }
    return a;
}
public static void main(String[] args) {
    int[][] a = {
            {1, 2, 3, 4, 5, 6},
            {2, 3, 4, 5, 6, 7},
            {3, 4, 5, 6, 7, 8},
            {4, 5, 6, 7, 8, 9}};

    for (int[] row : a) {
        System.out.println(Arrays.toString(row));
    }

    System.out.println();

    for (int[] row : inner(a)) {
        System.out.println(Arrays.toString(row));
    }
}

标签: javaarraysmultidimensional-array

解决方案


在循环外创建一个新数组,然后通过转换两个数组之间的索引来填充循环内的数组:

public static int[][] inner (int[][] a) {
    int rowL = a.length - 1;
    int colL = a[1].length -1;
    int[][] ret = new int[rowL - 1][colL - 1];

    for (int row = 1; row < rowL; row++) {
        for (int col = 1; col < colL ; col++) {
            ret[row - 1][col - 1] = a[row][col];
        }
    }

    return ret;
}

推荐阅读