Brandon Finley
Brandon Finley

Reputation: 127

How do I get the length of the secondary field in a 2d array?

I wanted to print the length of the second 10 in field 2d array, but I didn't know how. I want to create another for loop inside of this one and have it count to its length.

public class Main {

    public static void main(String[] args) {

        Object[][] field = new Object[10][10];

        for (int i = 0; i < field.length; i++) {
            System.out.println("Length: " + i);
        }

        System.out.println("Goodbye.");
    }

}

Upvotes: 1

Views: 73

Answers (4)

John Luo
John Luo

Reputation: 11

field is an array containing other arrays of 10 length each. Doing field[i] will get the array at index i from field. Therefore using field[i].length will get the length of the array at index i. tho count the lengths of all the arrays inside field you would use:

public class Main {

   public static void main(String[] args) {

        Object[][] field = new Object[10][10];

        for (int i = 0; i < field.length; i++) {
            System.out.println("Length: " + field[i].length);
        }

        System.out.println("Goodbye.");
    }

}

Upvotes: 0

Nathan Fiori
Nathan Fiori

Reputation: 1

Another way you could approach this using a nested for loop, as you requested. The solution would look something like this.

for( int r = 0; r<field.length; r++ ) {
    System.out.println("Length: " + r);
    for( int c = 0; c<field[0].length; c++) {
        System.out.println("Length: " + c);
    }
}

The console messages may not be what you wanted but the header for how long the loop runs would be c<field[0].length;

Hope this helps.

Upvotes: 0

UsamaAmjad
UsamaAmjad

Reputation: 4604

Its kind of two-dimensional array and you can get the length of second array like this field[i].length and use it in your nested loop.

public static void main(String[] args) {

        Object[][] field = new Object[10][10];

        for (int i = 0; i < field.length; i++) {
            System.out.println("Total Rows: " + field.length);
            for(int j = 0; j < field[i].length; j++){
               System.out.println("Row: " + i);
               System.out.println("Length: " + field[i].length);
            }
        }

        System.out.println("Goodbye.");
    }

Upvotes: 1

Malt
Malt

Reputation: 30285

field is a matrix, which is an array of arrays. That means that field[i] is an array. Specifically, an array of Object. If you want that array's length, you just call .length

So the answer is System.out.println("Length: " + field[i].length);

Upvotes: 1

Related Questions