2011-04-04 86 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 <字符串,整数>();

享受,博罗。