简体   繁体   中英

Make the loop results appear in an array through Arrays.toString in Java

I wrote a code extracting the middle values of the array but I have no idea, how to make the second array look properly through Arrays.toString() .

It looks as follows currently:

[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 7]
[3, 4, 5, 6, 7, 8]
[4, 5, 6, 7, 8, 9]
3 4 5 6
4 5 6 7

However it should be

[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 7]
[3, 4, 5, 6, 7, 8]
[4, 5, 6, 7, 8, 9]
[3, 4, 5, 6]
[4, 5, 6, 7]

Would appreciate your help.

import java.util.Arrays;

class array2d {
    public static void main(String args[]){
        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}};

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

        for(int i=1; i < 6; i++){
            for(int j=1; j < 5; j++){
                if (i == 1
                 || i == 2
                 || j == 0) {
                    System.out.print(arr[i][j]+" ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}
import java.util.Arrays;
class array2d { 
public static void main(String args[]){
    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}};

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


    for(int i=1; i < arr.length-1; i++){
        int middle[] = new int[arr[i].length-2];
        for(int j=1; j < arr[i].length-1; j++){
                middle[j-1] = arr[i][j];
        }
        System.out.println(Arrays.toString(middle));
    }

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM