2016-03-09 3 views
-1

Я работаю над программой Зла Виселица И по какой-то причине, я получаю эту ошибку:Зла Виселица Java Программа

What length word do you want to use? 4 
How many wrong answers allowed? 4 

guesses : 4 
guessed : [] 
current : ---- 
Your guess? e 
Exception in thread "main" java.lang.NullPointerException 
    at Game.HangmanManager.record(HangmanManager.java:142) 
    at Game.HangmanMain.playGame(HangmanMain.java:62) 
    at Game.HangmanMain.main(HangmanMain.java:42) 

Вот моя программа:

package Game; 

import java.util.*; 

public class HangmanManager 
{ 

    private String pattern; 
    private int max; 
    private int length; 
    private SortedSet<Character> guessesMade; 
    private Set<String> currentWords; 
    private Map<String, Set<String>> patternMap; 

    public HangmanManager(List<String> dictionary , int length, int max) 
    { 
     this.max = max; 
     this.length = length; 


     if(length < 1 && max < 0) 
      { 
       throw new IllegalArgumentException(); 

      } 

     words = new TreeSet<String>(); 
     guessesMade = new TreeSet<Character>(); 
     currentWords = new TreeSet<String>(); // current words =(words) 
     patternMap = new TreeMap<String, Set<String>>(); // patternMAP = < pattern, words> 

     for (String word : dictionary) 
     { 
      if (word.length() == length) 
      { 
      words.add(word); // if length of the word matches a word with the same length it will be added 
      } 

     } 

    } 


    public Set<String> words() 
    { 
     return words; 
    } 


    public int guessesLeft() 
    { 
     return max - guessesMade.size(); 
    } 



    public SortedSet<Character> guesses() 
    { 
     return guessesMade; 
    } 


    public String pattern() 
    { 
     if (words.isEmpty()) 
     { 
      throw new IllegalArgumentException("Invalid No Words"); 
     } 
     pattern = " "; // blank for now 
     for (int i = 0; i < length; i++) 
     { 
      pattern += "-"; // will have a "-" for how long the length of the word is 
     } 

     return pattern; // will return the number of lines 
    } 


    public int record(char guess) 
    { 
      if (guessesLeft() < 1 || words.isEmpty()) 
      { 
       throw new IllegalStateException(); 
      } 

      if (!words.isEmpty() && guessesMade.contains(guess)) 
      { 
       throw new IllegalArgumentException(); 
      } 

      guessesMade.add(guess); // guess 
      int occurences = 0; 

      for(String word: words) 
      {   
       if(patternMap.containsKey (pattern)) 
       { 

        occurences = generatePattern(word, guess); // the word including the guess letter will fill in the blank spots 
        currentWords.add(word); // the word will be added to the possibilities 
        currentWords = patternMap.get(pattern); // the word will be able to fill once the guesses are made 
//     if(patternMap.get(pattern)!=null) 
//      { 
//       currentWords = patternMap.get(pattern); 
//       
//      } 
        patternMap.put(pattern, currentWords); 
       } 
       else 
       { 
       currentWords.add(word); 
       patternMap.put(pattern, currentWords); 
       } 
      } 

     words = find(); 
     return occurences; 
    } 


    private Set<String> find() 
    { 
     int maxSize = 0; 

     Map <String, Integer> patternCount = new TreeMap<String, Integer>(); 

     for (String key : patternMap.keySet()) // keyset equals word 
     { 
      patternCount.put(key, patternMap.get(key).size()); // size of the word 

       if (patternMap.get(key).size() > maxSize) 
       { 
        maxSize = patternMap.get(key).size(); 
        pattern = key; // pattern will becomes based on the word 
       } else if (patternMap.get(key).size() == maxSize) 
       { 
        if (key.length() >= pattern.length()) 
        { 
         pattern = key; 
         maxSize = patternMap.get(key).size(); // the pattern is now the word key 
        } 
       } 
      } 
     System.out.println("Current pattern: " + pattern); 

     return patternMap.get(pattern); // the pattern that will becomes now that the word was picked 
    } 

    private int generatePattern(String s, char guess) 
    { 
     int count = 0; 
     pattern = ""; 
      for (int i = 0; i < length; i++) 
      { 
       if (s.charAt(i) == guess) 
       { 
        pattern += guess + " "; 
        count++; 
       } else 
       { 
        pattern += "- "; 
       } 
      } 
     return count; 
    } 

} 

ошибка, кажется, происходит в метод записи для:

patternMap.put(pattern, currentWords); на линии 149

я побежал отладчик много раз, и я замечаю, что если вы будете следовать программе, вы увидите, что currentWords становится Null в конце концов после того, как программа пробегает слова через один раз, даже если я создаю экземпляр, и я создал карту для patternMap.

Если кто-нибудь может сказать мне, что делать и что нужно изменить, я действительно ценю это, потому что я так потерял с этим

+3

Ваш код является неполным и не будет компилировать, это означает, что ваш вопрос либо будет закрыт как дубликат [Что такое исключение Null Pointer , и как его исправить?] (http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) или «Почему мой код не работает - без предоставления запускаемого примера « – MadProgrammer

+0

Я могу предоставить программу HangmanMain и текстовый файл словаря – Jay

ответ

0

patternMap является TreeMap. Как вы сказали, ваша проблема с patternMap.put(pattern, currentWords); на линии 149. Согласно JavaDocs для TreeMap, put() бросает NullPointerException ...

if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys

Поскольку TreeMap<String,Object> использует естественный порядок из его ключей (т.е. String), проблема в том, это pattern есть null. Почему вы не просто инициализировать pattern значение по умолчанию:

private String pattern = " "; 
+0

Хорошо, что currentWords имеет значение null, а не шаблон – Jay

+0

' patternMap.put (pattern, null); 'отлично действует при условии, что 'pattern! = null'. –

+0

Хорошо, я исправил это, я верю, но теперь у меня есть новая проблема – Jay

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