如何迭代遍历二维数组并搜索 [ ] [Name]?
当找到 Name 时,应返回索引以便我可以更改该数组中的值。
[Index] [Values]。
此外,存储到找到的数组的语法是什么?[ ] [index]。循环通过索引并设置值。[0] [1] = blah。
谢谢。
private Point find2DIndex(Object[][] array, Object search) {
if (search == null || array == null) return null;
for (int rowIndex = 0; rowIndex < array.length; rowIndex++ ) {
Object[] row = array[rowIndex];
if (row != null) {
for (int columnIndex = 0; columnIndex < row.length; columnIndex++) {
if (search.equals(row[columnIndex])) {
return new Point(rowIndex, columnIndex);
}
}
}
}
return null; // value not found in array
}
这将仅返回第一个匹配项。如果需要全部,可以将所有点收集到列表中,并在最后返回该列表。
用法:
private void doSomething() {
String[][] array = {{"one", "1"},{"two","2"}, {"three","3"}};
Point index = find2DIndex(array, "two");
// change one value at index
if (index != null)
array[index.x][index.y] = "TWO";
// change everything in the whole row
if (index != null) {
String[] row = array[index.x];
// change the values in that row
}
}
根据您的评论进行更新:
for(String[] subarray : array){
int foundIndex = -1;
for(int i = 0; i < subarray.length; i++){
if(subarray[i].equals(searchString)){
foundIndex = i;
break;
}
}
if(foundIndex != -1){
// change all values that are not at position foundIndex
for(int i = 0; i < subarray.length; i++){
if(i != foundIndex){
subarray[i] = "something";
}
}
break;
}
}
for(int xIndex = 0 ; xIndex < 3 ; xIndex++){
for(int yIndex = 0 ; yIndex < 3 ; yIndex++){
if(arr[xIndex][yIndex].equals(stringToSearch)){
System.out.println("Found at"+ xIndex +"," + yIndex);
for(int remainingIndex = 0 ; remainingIndex < 3 ; remainingIndex++ ){
arr[xIndex][remainingIndex]="NEW VALUES";
}
break;
}
}
}
String [] [] matrix = ...
,那么第一维matrix [i]
的类型为String []
,而不是String
。 - Jean-Philippe Pellet