列表(LST):对,快速,棕色,狐狸,跳下,结束了,,懒惰,狗]遍历字符串列表以获取最短的单词?
我试图返回的最短字集合(犬,狐的。 )
public Collection<String> getShortestWords() {
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0; i < lst.size(); i++){
if(lst.get(i).length() > lst.get(i+1).length()){
newlist.add(lst.get(i+1));
}
}return newlist;
}
我不得不通过扫描文本文档这个工作,但我必须把它转换到一个列表中删除不必要的标点符号和数字。但是我犯了一个错误,所以现在我需要迭代一个列表而不是文件。
这是我的旧逻辑:
String shortestWord = null;
String current;
while (scan.hasNext()) { //while there is a next word in the text
current = scan.next(); //set current to the next word in the text
if (shortestWord == null) { //if shortestWord is null
shortestWord = current; //set shortestWord to current
lst.add(shortestWord); //add the shortest word to the array
}
if (current.length() < shortestWord.length()) { //if the current word length is less than previous shortest word
shortestWord = current; //set shortest word to the current
lst.clear(); //clear the previous array
lst.add(shortestWord); //add the new shortest word
}
else if(current.length() == shortestWord.length()){ //if the current word is the same length as the previous shortest word
if(!lst.contains(current))
lst.add(current);
}
}
return lst;
}
因此,将您的while循环更改为列表中的每个字符串。您不会使用'current',而是使用for循环中的变量集。 – gtgaxiola 2015-03-02 18:37:33