Let's say I have a main class in java that receives a matrix[][], like: `
public main[] findBall(int[][] grid) {
}
` And then the user enters the imput:
[[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]
I know it's a 5x5 but only because I saw what the user typed, how do I get the matrix size->(5x5) or any other size that they may type? or is there another way to navigate through it without knowing the size?
I tried nothing, I'm a beginner in Java so bear with me.
CodePudding user response:
Understand matrices in Java more as an array of arrays. grid
is an Array and will have a length, grid.length
. Each entry of the grid is an Array with a length, so grid[0].length
is the length of the first column. Assuming that every entry is of the same length, your matrix size will be grid.length
x grid[0].length
CodePudding user response:
If you are provided with an array and don't know its size, then you can also use its length with the Array property which is ("array-Variable").length and it will give you the length of the array. If you are working with a 2-D array then for the no. of rows you can use ("matrix-Variable").length and for the number of columns, you have to check the length of each row or 1st row by using ("matrix-Variable")[i].length where i can be either 0 or any number given the number is in range of the total number of rows.