列表(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