在Java中搜索一个二维数组

9

如何迭代遍历二维数组并搜索 [ ] [Name]?

当找到 Name 时,应返回索引以便我可以更改该数组中的值。

[Index] [Values]。

此外,存储到找到的数组的语法是什么?[ ] [index]。循环通过索引并设置值。[0] [1] = blah。

谢谢。


3
请重新表达您的问题。在Java中,“二维数组”只是数组的数组,因此如果您有String [] [] matrix = ...,那么第一维matrix [i]的类型为String [],而不是String - Jean-Philippe Pellet
3个回答

8
有时把搜索功能放在一个单独的方法中会更加简便和清晰:
 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
  }

}

3

根据您的评论进行更新:

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;
   }
}

我更新了我的答案,这样你就可以知道找到字符串的索引了。 - morja

3
最基本的方法是:
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;
      }
}
}

谢谢。这是我问题的一半。;P 如果我找到了searchedItem,那么如何设置该数组的其余值呢?假设searchedItem在[0][0],则searchedItem将在所有数组的索引0处。[0][0],[1][0]等。然后,我想编辑[0][1],[0][2],[0][3]的值?谢谢 - some_id
@alJaree,你只需要在if语句内部迭代其他循环来进行编辑,让我更新。 - jmj
谢谢。我已经将值硬编码到变量中。这些值以二进制形式发送到套接字中。因此,它们被转换为字符串,拆分,然后每个标记都设置为一个变量。我想将找到的数组的索引设置为这些值。我知道变量的索引。[foundArray] [name] = 名称,[foundArray] [size] = 大小等。在循环外使用找到的数组索引在哪里?谢谢 - some_id
没关系。Andreas 回答得很正确。感谢你的帮助。 - some_id

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接