Java int[][] 数组 - 迭代和查找值
我有一个 'int[][]
' 形式的数组,它表示一个小网格的坐标.每个坐标都被分配了自己的值.例如 array[0][4] = 28
......
I have an array in the form of 'int[][]
' that represents the co-ordinates of a small grid. Each co-ordinate has been assigned its own value. eg array[0][4] = 28
......
我有两个问题.首先,我如何遍历所有存储的值.其次,我希望能够输入一个值并返回其在网格中的特定坐标.解决这个问题的最佳方法是什么?
I have two questions. Firstly, how do I iterate through all the stored values. Secondly, I want to be able to input a value and have its specific co-ordinates in the grid returned. What would be the best way to approach this?
感谢您的帮助!
推荐答案
您可以使用 for 循环或增强的 for 循环进行迭代:
You can iterate with either for loops or enhanced for loops:
for (int row=0; row < grid.length; row++)
{
for (int col=0; col < grid[row].length; col++)
{
int value = grid[row][col];
// Do stuff
}
}
或
// Note the different use of "row" as a variable name! This
// is the *whole* row, not the row *number*.
for (int[] row : grid)
{
for (int value : row)
{
// Do stuff
}
}
第一个版本将是查找坐标"问题的最简单解决方案 - 只需检查内部循环中的值是否正确.
The first version would be the easiest solution to the "find the co-ordinates" question - just check whether the value in the inner loop is correct.
相关文章