使用嵌套的for循环修改2D数组 [英] Modifying a 2D array using a nested for loop

查看:151
本文介绍了使用嵌套的for循环修改2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印2D数组的中间"(a).例如,对于代码中的给定数组,我要打印:

I am trying to print out the 'middle' of the 2D array (a). For example, for given arrays in my code, I would like to print:

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

但是我只能打印中间"值.我想在内部方法中修改2D数组(a)并在main中打印它,而不要在嵌套的for循环中使用System.out.println.我将如何去做?

However I was only able to print out the 'middle' values. I would like to modify the 2D array (a) in the method inner and print it in main instead, and not use System.out.println in the nested for loop. How would I go about doing this?

这是我的代码:

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));
    }
}

推荐答案

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

Create a new array outside the loop and then fill that array inside the loop by translating the indices between the two arrays:

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;
}

这篇关于使用嵌套的for循环修改2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆