2014-10-01 2 views
1

Я сделал следующие десятки раз:запись не определена в HashMap итерации цикла

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; 
    } 
} 
+3

Какое сообщение об ошибке? – manouti

+0

Какая IDE вы используете? –

+1

Открыть/закрыть вашу среду IDE Clean/Build your Project – gtgaxiola

ответ

2

У Вас есть ошибка в вашем тройном оператора, который путает компилятор:

bestKey =() ? bestKey : currentKey; 

Вы забыли поставить условие в скобки.

мне удалось воссоздать эту ошибку с помощью небольшого примера (я использовал карту с различными типами ключей и значений, но это не имеет значения):

for (Map.Entry<Key, WordSet> entry : topWordCountSets.entrySet()) { 
    Key currentKey = entry.getKey(); // fake error 
    Key bestKey =() ? null : null; // real error 
    } 

Это делает компилятор показывает две ошибки, один для entry и один для (). Если вы исправите ошибку () (например, изменив ее на (true)), обе ошибки исчезнут. Я понятия не имею, почему компилятор сообщает об ошибке на entry.

+0

Странно ... Я пробовал то же самое и получил только ошибку в лучшем случаеKey =()? bestKey: currentKey; Arch Linux с openjdk. Было бы интересно узнать, какая версия java у OP была – user

+0

@user. Я не знаю, но я воссоздал ее на Java 6 на Eclipse Juno. – Eran

+0

* Голова Бонкс несколько раз против стены * Вау, спасибо. Я даже не думал смотреть дальше. Я бы ожидал ошибку компиляции только на тернаре. – AaronF

Смежные вопросы