Java – returns the number of rows in a 2D array?

I have this 2D array:

private boolean[][] landscape;

This landscape array defines a pond with [rows] and [cols]

The public int getrows() method needs to return the number of rows in the pattern array

I tried to go back to landscape length; That doesn't work Combined with more things I tried, I didn't succeed:

int count = 0;
        for (boolean[] i : landscape){
            count += i.length;


        }
        return count;

and

int count = 0;

        for (int i = 0; i < landscape.length; i++) {

                if (landscape[i] != null){
                    count ++;

            }

        }
        return count;

The number of rows and columns depends on what the user selects At least 5 So what should I do?

Solution

Let's start with some definitions:

We assume that the 3 x 4 rectangular array has 3 columns and 4 rows, which is expressed by the following formula:

boolean landscape[][] = new boolean[3][4];

To get the number of rows and columns:

int nosRows = landscape[0].length;  // 4
int nosCols = landscape.length;     // 3

If you think I've mixed rows and columns, rename them (mentally) (there is no general convention on which dimension represents columns and rows.)

If you expect answers other than 3 or 4, you need to explain what you're talking about

Obviously, this applies only to square and rectangular arrays

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>