Java int [] [] array - 迭代并查找值 [英] Java int[][] array - iterating and finding value
问题描述
我有一个' 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.
这篇关于Java int [] [] array - 迭代并查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!