I have this 2d array:
private boolean[][] landscape;
this landscape array defines a pond with its [rows] and [cols]
The method, public int getRows()
, needs to return the number of rows in the landscape array
I tried just return landscape.length;
and that didnt work. Couple more things I tried without success:
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 amount of rows and cols depends on what the user selects I believe. There is a minimum of 5. So how would i do this?
Lets start with some definitions:
Let us assume that a 3 x 4
rectangular array has 3 columns and 4 rows and is represented by:
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 got rows and columns the wrong way around in my terminology, mentally rename them. There is no universal convention about which dimension represents the columns and which represents the rows in Java code.
If you are expecting some answer other than 3 or 4, you will need to explain what you are talking about.
Obviously, this only works for square or rectangular arrays.
So 2D arrays are really just arrays of arrays. So if I have a 2D array with 5 rows and 4 columns, you could think of it as an array containing 5 subarrays that have 4 spots each.
boolean landscape[][] = new boolean[5][4];
int numRows = landscape.length;
int numCols = landscape[0].length;
System.out.println("Number of rows: " + numRows);
System.out.println("Number of cols: " + numCols);
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(landscape[i][j]);
}
System.out.println("");
}
Output:
Number of rows: 5
Number of cols: 4
0000
0000
0000
0000
0000
It is important to note that java is considered row major (the row always comes first): Which comes first in a 2D array, rows or columns? This is important because if you iterate column first (column 0: row 0, row 1, row 2, row 3, row 4; column 1: row 0, row 1, etc.), you are actually going through the 2D array inefficiently, because the memory is stored consecutively row by row, so doing it column by column means you are skipping over segments of memory and then going back, instead of just going consecutively; read about assemblers and compilers for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With