Length for each dimension in bidimensional arrays in Java

337 views Asked by At

I suppose that there exists a way to know the length of each dimension in multidimensional arrays. I have the following code and in the for conditional I would like to change the condition so that it works for every array.

import javax.swing.JOptionPane;

public class Arrays_bidimensionales {

    public static void main(String[] args) {
        int[][] matriz1 = new int[4][5];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 5; j++) {
                matriz1[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Introduce el valor para la posiciĆ³n" + i + "." + j));
                System.out.print(" " + matriz1[i][j] + " ");
            }
            System.out.println();
        }
    }
}

I have tried with matriz1.length but only seems to work with arrays with a unique dimension.

2

There are 2 answers

1
Mureinik On BEST ANSWER

Arrays in Java have a length property, so you could dynamically query an array's length, even if it's a multidimensional jagged array:

int [][] matriz1 = // initialized somehow...
for (int i = 0 ; i < matriz1.length ; i++) {
    for (int j = 0 ; j < matriz1[i].length; j++) {
        // Do something with matriz1[i][j]
0
Raman Sahasi On

Your 2D array looks something like this

int[][] matriz1 = new int[4][5];

  1. To get the length of first dimension, you can use

    int length1 = matriz1.length; //length1 = 4
    

    this will give you 4.

    int[][] matriz1 = new int[4][5]; //this way you're refering to the first dimension
                              ^
    
  2. To get the length of second dimension, just find the length of any element from first dimension. Here's an example using zeroth index

    int length2 = matriz1[0].length; //length2 = 5
    

    this will give you 5.

    int[][] matriz1 = new int[4][5]; //this way you're refering to second dimension
                                 ^