2011-04-04 84 views
0

我需要關於如何存儲句子中出現的特定單詞索引的幫助。 我需要將索引存儲在數組中,以便稍後可以訪問它。我正在使用while循環,但它不工作。將索引存儲在數組中

while (index > 0) { 

      for (int i = 0; i < data.length; i++) { 

       data[i] = index; 

      } 

      System.out.println("Index : " + index); 


      index = input.indexOf(word, index + word.length()); 

     } 
+0

您可以添加有關您正在嘗試完成的內容,您希望數據保存的內容以及初始化哪個索引的詳細信息? – 2011-04-04 20:16:15

+0

@Stephen L:[這是原始問題](http://stackoverflow.com/questions/5533164/of-times-a-single-word-in-a-sentence/5533329)。 – mre 2011-04-04 20:30:56

回答

0

我已經評論過您的代碼。請閱讀評論以瞭解。

while (index > 0) { //String.indexOf can return a 0 as a valid answer. Use -1. 
//Looping over something... Why don't you show us the primer code? 
    for (int i = 0; i < data.length; i++) { 
     /* 
     Looping over the `data` array. 
     You're filling every value of `data` with whatever is in `index`. Every time. 
     This is not what you want. 
     */  
     data[i] = index; 
    } 

    System.out.println("Index : " + index); 
    //OK 
    index = input.indexOf(word, index + word.length()); 
} 

ArrayList替換你的數據數組和相關的循環。對於您找到的每個索引,使用ArrayList.add()

0

如果你問你會用,那麼我建議去一個地圖的字符串(單詞的名稱)列出整數的結構類型(這些詞的索引)。

下面的類顯示了我如何實現一個地圖存儲列表。



import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Set; 

/** 
* Class of a map which allows to have a list of items under a single key. 
* @author Konrad Borowiecki 
* 
* @param <T1> type of the key. 
* @param <T2> type of objects the value list will store. 
*/ 
public class ListHashMap<T1, T2> extends HashMap<T1, List<T2>> 
{ 
    private static final long serialVersionUID = -3157711948165169766L; 

    public ListHashMap() 
    { 
    } 

    public void addItem(T1 key, T2 item) 
    { 
     if(containsKey(key)) 
     { 
      List<T2> tml = get(key); 
      tml.add(item); 
     } 
     else 
     { 
      List<T2> items = new ArrayList<T2>(); 
      items.add(item); 
      put(key, items); 
     } 
    } 

    public void removeItem(T1 key, T2 item) 
    { 
     List<T2> items = get(key); 
     items.remove(item); 
    } 

    public void removeItem(T2 item) 
    { 
     Set<java.util.Map.Entry<T1, List<T2>>> set = entrySet(); 
     Iterator<java.util.Map.Entry<T1, List<T2>>> it = set.iterator(); 

     while(it.hasNext()) 
     { 
      java.util.Map.Entry<T1, List<T2>> me = it.next(); 
      if(me.getValue().contains(item)) 
      { 
       me.getValue().remove(item); 
       if(me.getValue().isEmpty()) 
        it.remove(); 
       break; 
      } 
     } 
    } 
} 

你的情況,你會的單詞映射到索引列表,這樣,你會調用類是這樣的: ListHashMap <字符串,整數> wordToIndexesMap =新ListHashMap <字符串,整數>();

享受,博羅。