我做了以下几十次:
for(Map.Entry<Key, WordSet> entry : topWordCountSets.entrySet()) {
Key currentKey = (entry.getKey());
}
但是,entry
中的entry.getKey()
显然未定义。我没有在循环外的任何地方定义它,所以没有碰撞。
这里有更多代码(由于未定义条目,因此未完成最佳算法。):
package hangman;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
public class Partitions {
private int _wordLength = 2;
private WordSet _L;
private HashMap<Key, WordSet> _partitions = new HashMap<Key, WordSet>();
public void initialize(InputStream stream, int wordLength) throws Exception {
_L = WordSetParser.generate(stream,wordLength);
}
private void _partition(char by) throws Exception {
_partitions.clear();
Iterator<Word> iterator = _L.iterator();
while(iterator.hasNext()) {
Word nextWord = iterator.next();
if(nextWord.length() == _wordLength) {
Key nextKey = new Key(nextWord, by);
if(!_partitions.containsKey(nextKey)) {
_partitions.put(nextKey, new WordSet(_wordLength));
}
_partitions.get(nextKey).add(nextWord);
}
}
}
public WordSet getBestPartition(char by) throws Exception {
//Establish partitions
_partition(by);
//Find partitions with greatest number of words
HashMap<Key, WordSet> topWordCountSets = new HashMap<Key, WordSet>();
int maxWords = 0;
for(Map.Entry<Key, WordSet> entry : _partitions.entrySet()) {
if(entry.getValue().size() > maxWords) {
maxWords = entry.getValue().size();
topWordCountSets.clear();
topWordCountSets.put(entry.getKey(), entry.getValue());
}
else if(entry.getValue().size() == maxWords) {
topWordCountSets.put(entry.getKey(), entry.getValue());
}
}
if(topWordCount.size() == 1)
return (WordSet)topWordCountSets.values().toArray()[0];
else {
//Find partitions with best key
Key bestKey = null;
for(Map.Entry<Key, WordSet> entry : topWordCountSets.entrySet()) {
Key currentKey = (entry.getKey());
if(bestKey == null)
bestKey = currentKey;
else if(currentKey.count() == 0 && bestKey.count() != 0)
bestKey = currentKey;
else if(currentKey.count() != bestKey.count())
bestKey = () ? bestKey : currentKey;
}
}
return null;
}
}
答案 0 :(得分:3)
您的三元运算符中出现错误,导致编译器混淆:
bestKey = () ? bestKey : currentKey;
您忘记在括号内添加条件。
我设法用一个小例子重新创建了这个错误(我实际上使用了具有不同类型的Key和Value的地图,但它没有区别):
for (Map.Entry<Key, WordSet> entry : topWordCountSets.entrySet ()) {
Key currentKey = entry.getKey (); // fake error
Key bestKey = () ? null : null; // real error
}
这使编译器显示两个错误,一个用于entry
,另一个用于()
。如果您修复了()
错误(例如将其更改为(true)
),则两个错误都会消失。我不知道为什么编译器会在entry
报告错误。