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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible to modify the existing array (a) inside the inner method instead of creating a new one?
@neaf No, the size of an array cannot be changed after it is created.
@neaf I suggest you learn about List and ArrayList if you need a structure that can change its size.
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 Please post a new question with a minimal reproducible example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.