Java 使用嵌套for循环修改二维阵列

Java 使用嵌套for循环修改二维阵列,java,arrays,multidimensional-array,Java,Arrays,Multidimensional Array,我试图打印出2D数组(a)的“中间”。例如,对于代码中的给定数组,我希望打印: [3,4,5,6] [4,5,6,7] 然而,我只能打印出中间值。我想修改方法inner中的2D数组(a),改为在main中打印,而不是在嵌套for循环中使用System.out.println。我该怎么做呢 这是我的密码: 公共静态int[][]内部(int[][]a){ int rowL=a.长度-1; int colL=a[1]。长度为-1; 对于(int row=1;row

我试图打印出2D数组(a)的“中间”。例如,对于代码中的给定数组,我希望打印:

[3,4,5,6]
[4,5,6,7]
然而,我只能打印出中间值。我想修改方法inner中的2D数组(a),改为在main中打印,而不是在嵌套for循环中使用System.out.println。我该怎么做呢

这是我的密码:

公共静态int[][]内部(int[][]a){
int rowL=a.长度-1;
int colL=a[1]。长度为-1;
对于(int row=1;row
publicstaticvoidmain(字符串[]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}};
对于(int[]行:a){
System.out.println(Arrays.toString(row));
}
System.out.println();
对于(int[]行:内部(a)){
System.out.println(Arrays.toString(row));
}
}

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

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;
}
公共静态int[][]内部(int[][]a){
int rowL=a.长度-1;
int colL=a[1]。长度为-1;
int[][]ret=新int[rowL-1][colL-1];
对于(int row=1;row
如果您只想打印中间值(我对这个代码示例的定义是:middle=完整数组减去第一个和最后一个元素),您可以使用
StringBuilder

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[] b : a) {
        // create a String output for each inner array
        StringBuilder outputBuilder = new StringBuilder();
        // append an introducing bracket
        outputBuilder.append("[");
        // make the values to be printed ignore the first and last element
        for (int i = 1; i < b.length - 1; i++) {
            if (i < b.length - 2) {
                /*
                 * append a comma plus whitespace 
                 * if the element is not the last one to be printed
                 */
                outputBuilder.append(b[i]).append(", ");
            } else {
                // just append the last one without trailing comma plus whitespace 
                outputBuilder.append(b[i]);
            }
        }
        // append a closing bracket
        outputBuilder.append("]");
        // print the result
        System.out.println(outputBuilder.toString());
    }
}
您可以使用方法在数组的给定范围内迭代:

int[]arr={
{1, 2, 3, 4, 5, 6},
{2, 3, 4, 5, 6, 7},
{3, 4, 5, 6, 7, 8},
{4, 5, 6, 7, 8, 9}};
int[]middle=Arrays.stream(arr,1,arr.length-1)
.map(行->数组.stream(行,1,行.length-1)
.toArray())
.toArray(int[]]::新建);
//输出
Arrays.stream(中间).map(Arrays::toString.forEach(System.out::println);

我希望进行修改,以便在最后打印2D数组而不是字符串、整数等。我不明白您如何
返回ret[3, 4, 5, 6]
[4, 5, 6, 7]