2010-12-07 82 views
8

如何迭代通過二維數組搜索[] [Name]?在java中搜索2維數組

當找到名稱時,應該返回索引,以便我可以更改該數組中的值。

[Index] [Values]。

此外,語法如何查找存儲到數組中找到? [] [index]。循環索引並設置一個值。 [0] [1] =等等。

感謝

+3

請重新制定你的問題。 Java中的「二維數組」只是數組的數組,所以如果你有`String [] [] matrix = ...`,那麼第一個維`矩陣[i]`的類型是`String []`,而不是`String`。 – 2010-12-07 13:14:05

回答

7

有時更容易,總是清潔劑把搜索在一個單獨的方法:

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

我更新了我的答案,以便您將索引找到字符串。 – morja 2010-12-07 13:44:53

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

謝謝。這是我的一半問題。 ; P所以,如果我找到了SearchingItem我該如何設置該數組的其餘值。讓我們說searchingItem是在[0] [0] searchingItem將在所有數組的索引0。然後我想編輯[0] [1],[0] [2],[0] [3]的值。[0] [0] [1] [0]謝謝 – jarryd 2010-12-07 13:32:56