【发布时间】:2015-05-10 04:51:39
【问题描述】:
我有一个排序的规范词列表,我想用迭代器迭代列表以找到匹配的规范词,这些词将具有相同的 Anagrams,然后将它们添加到单独的 LinkedList 中,如果它们匹配则配对在一起。我该怎么做呢?我是否会同时为同一个列表运行两个迭代器,并将它们放入嵌套的 while 循环中,第一个元素上有一个迭代器,第二个迭代器在同一个列表中搜索所有元素以进行匹配,然后如果匹配则将其添加到列表中成立?有什么想法吗?
这是我到目前为止所做的:
驱动类文件:
import java.util.*;
import java.io.*;
public class Programming9Driver {
public static void main(String[] theArgs) {
LinkedList<Word> wordObjects = new LinkedList<Word>();
ArrayList<String> localWords = new ArrayList<String>();
BufferedReader localInput = null;
BufferedWriter localOutput = null;
try {
String localLine;
localInput = new BufferedReader(new FileReader("words.txt"));
// localOutput = new BufferedWriter(new FileWriter("out9.txt"));
while ((localLine = localInput.readLine()) != null) {
if (localLine != "") {
localWords.add(localLine);
}
//
//
}
/*
*/
localInput.close();
// localOutput.close();
} catch (Exception e) {
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
localWords.removeAll(Collections.singleton(""));
Map<String, List<String>> anagramList = new HashMap<String, List<String>>();
Iterator<String> iterAdd = localWords.iterator();
while (iterAdd.hasNext()) {
wordObjects.add(new Word(iterAdd.next()));
}
Collections.sort(wordObjects);
LinkedList<AnagramFamily> anagramObjects = new LinkedList<AnagramFamily>();
}
}
Word.java:
import java.util.*;
public class Word implements Comparable<Word>{
private String myWord;
private String myCanon;
private Map<String, List<String>> myCanonKey = new HashMap<String, List<String>>();
public Word(final String theWord) {
myWord = theWord;
myCanon = canonForm();
myCanonKey = canonWords();
}
public String canonForm() {
String canonWord = "";
Character[] localChars = new Character[myWord.length()];
for (int i = 0; i < localChars.length; i++) {
localChars[i] = myWord.charAt(i);
}
Arrays.sort(localChars);
for (int i = 0; i < localChars.length; i++) {
canonWord += localChars[i];
}
return canonWord;
}
public Map<String, List<String>> canonWords() {
ArrayList<String> canonList = new ArrayList<String>();
Map<String, List<String>> canonKey = new HashMap<String, List<String>>();
canonList.add(myWord);
canonKey.put(myCanon, canonList);
return canonKey;
}
public int compareTo(Word theOther) {
int result = canonForm().compareTo(theOther.canonForm());
return result;
}
public String toString() {
String result = "";
result = myWord;
if (myWord == "" || myCanon == "") {
result = "";
}
return result;
}
}
如何从我的主驱动程序调用以使用 Word 类 java 文件中的 canonWords() 方法?
【问题讨论】:
-
请告诉我们您已经尝试过什么。
-
发布了我的代码我想我只需要了解如何从 Word.java 类的原始驱动程序中更新 Map。
标签: java loops linked-list anagram