1

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]

However I was only able to print out the 'middle' values. I would like to modify the 2D array (n) according to the explanation and print it instead. How would I go about doing this?

Here is my code:

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]);
            
        }
        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));
       }
     
}
Community
  • 1
  • 1
neaf
  • 67
  • 4

1 Answers1

1

First, you need to create a new empty array with the correct size. Then you fill in the values of the new array instead of printing them.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Is it possible to modify the existing array (a) inside the inner method instead of creating a new one? – neaf Nov 19 '19 at 21:27
  • 2
    @neaf No, the size of an array cannot be changed after it is created. – Code-Apprentice Nov 19 '19 at 21:28
  • 1
    @neaf I suggest you learn about `List` and `ArrayList` if you need a structure that can change its size. – Code-Apprentice Nov 19 '19 at 21:30
  • Ok, I got you, thanks! One thing, would you care to explain why code `for ( int[] row : inner(a) ) { System.out.println(Arrays.toString(row)); }` is printing out this: `3456 4567 [1, 2, 3, 4, 5, 6] [2, 3, 4, 5, 6, 7] [3, 4, 5, 6, 7, 8] [4, 5, 6, 7, 8, 9]` – neaf Nov 20 '19 at 08:30
  • @neaf Please post a new question with a [mcve] – Code-Apprentice Nov 20 '19 at 16:38