2017-05-03 7 views
1

私は学校でプログラミングクラスのプロジェクトを行っています。ここでは、コンピュータが単語を選択しない限り、悪意のあるハンマーマンゲームを行うことになっています。ユーザーが公平に遊んでいると思うようにするために、コンピュータは同じ文字パターンの単語のみを考慮します。配列がArrayIndexOutOfBoundsExceptionを取得するのはなぜですか?

私は、 "a"と "e"という文字を推測した後に、ArrayIndexOutOfBoundsExceptionを持っていて、過去数時間、デバッガを使って調べようとしていましたが、まだ問題が見えず、クラス全体が最初の手紙のために働いていますが、それはちょうど2番目の手紙を壊すことを意味します。これは、HangmanManagerクラスの最後にpatternArr [indexOfMax]を返すと発生します。なぜ私はそれが期待どおりに動作していないのですか?

これは私が(あなたがゲームが動作することで言葉の束を持つテキストファイルを使用する必要があります)を使用されている辞書ファイルへのリンクです:http://www-personal.umich.edu/~jlawler/wordlist.html

は今ここに私のプログラムは次のとおりです。

HangmanManagerクラス

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.List; 
import java.util.Set; 
import java.util.SortedSet; 
import java.util.TreeSet; 

public class HangmanManager { 
    private SortedSet<String> wordset; 
    private SortedSet<Character> guessSet; 
    private String wordPattern; 
    private int guessesLeft; 



    public HangmanManager(List<String> dictionary, int length, int max){ 
     if(length < 1 || max < 0) { 
      throw new IllegalArgumentException(); 
     } 
     wordset = new TreeSet<String>(); 
     for(String words: dictionary) { 
      if(words.length() == length) { 
       wordset.add(words); 
      } 
     } 
     wordPattern = ""; 
     for (int i = 0; i < length; i++) { 
      wordPattern += "- "; 
     } 
     guessesLeft = max; 
     guessSet = new TreeSet<Character>(); 

    } 
    //Returns the managers words 
    public Set<String> words() { 
     return wordset; 
    } 

    //Returns the number of guesses left 
    public int guessesLeft() { 
     return guessesLeft - guessSet.size(); 
    } 

    //Returns the guessed letters 
    public SortedSet<Character> guesses() { 
     return guessSet; 
    } 

    //Returns String pattern 
    public String pattern() { 
     return wordPattern; 
    } 
    public int record(char guess) { 
     guessSet.add(guess); 
     return comparePatterns(wordset, guess); 
    } 

    private String makePattern(char guess, String word) { 
     String position = ""; 
     char[] letters = word.toCharArray(); 
     for (int i = 0; i < word.length(); i ++) { 
      if (letters[i] == guess) { 
       position = position + guess + " "; 
      } else { 
       position = position + "- "; 
      } 
     } 
     return position; 
    } 
    //This method is supposed to take out all the patterns that don't match 
    // the String commonPattern 
    private int comparePatterns(SortedSet<String> mySet, char guess) { 
     String[] wordArray = new String[mySet.size()]; 
     wordArray = (String[]) mySet.toArray(wordArray); 
     String[] patternArray = new String[wordArray.length]; 
     List<String> tempList = new ArrayList<String>(); 
     for(int i = 0; i < wordArray.length; i++) { 
      patternArray[i] = makePattern(guess, wordArray[i]); 
     } 
     String commonPattern = getMostCommonPattern(guess, patternArray); 

     int rightGuess = 0; 
     for(int i = 0; i > commonPattern.length(); i ++) { 
      if(commonPattern.charAt(i) == guess) { 
       rightGuess++; 
      } 
     } 
     for(int j = 0; j < patternArray.length; j++) { 
      if(commonPattern.equals(patternArray[j])) { 
       tempList.add(wordArray[j]); 
      } 
     } 
     wordset.removeAll(wordset); 
     wordset.addAll(tempList); 
     return rightGuess; 
    } 
    //This method gets the most common pattern 

    //THIS METHOD BREAKS 
    private String getMostCommonPattern(char guess, String[] patternArr) { 
     List<String> patternList = Arrays.asList(patternArr); 
     int[] countArray = new int[patternArr.length]; 
     for(int i = 0; i < patternArr.length; i++) { 
      countArray[i] = Collections.frequency(patternList, patternArr[i]); 
     } 


     int max = 0; 
     int indexOfMax = 0; 
     for (int j = 0; j < countArray.length; j++) { 
      if(max < countArray[j]) { 
       max = countArray[j]; 
       indexOfMax = j; 
      } else if (max > countArray[j]) { 

      }else if (max == countArray[j]) { 

      } 
     } 

     return patternArr[indexOfMax]; 
    } 
} 

HangmanMainクラス

import java.util.*; 
import java.io.*; 

public class HangmanMain { 
    public static final String DICTIONARY_FILE = "C:\\Users\\Zoratu\\Desktop\\EvilHangman\\dictionary.txt"; 
    public static final boolean DEBUG = false; // show words left 

    public static void main(String[] args) throws FileNotFoundException { 
     System.out.println("Welcome to the cse143 hangman game."); 
     System.out.println(); 

     // open the dictionary file and read dictionary into an ArrayList 
     Scanner input = new Scanner(new File(DICTIONARY_FILE)); 
     List<String> dictionary = new ArrayList<String>(); 
     while (input.hasNext()) { 
      dictionary.add(input.next().toLowerCase()); 
     } 

     // set basic parameters 
     Scanner console = new Scanner(System.in); 
     System.out.print("What length word do you want to use? "); 
     int length = console.nextInt(); 
     System.out.print("How many wrong answers allowed? "); 
     int max = console.nextInt(); 
     System.out.println(); 

     // set up the HangmanManager and start the game 
     List<String> dictionary2 = Collections.unmodifiableList(dictionary); 
     HangmanManager hangman = new HangmanManager(dictionary2, length, max); 
     if (hangman.words().isEmpty()) { 
      System.out.println("No words of that length in the dictionary."); 
     } else { 
      playGame(console, hangman); 
      showResults(hangman); 
     } 
    } 

    // Plays one game with the user 
    public static void playGame(Scanner console, HangmanManager hangman) { 
     while (hangman.guessesLeft() > 0 && hangman.pattern().contains("-")) { 
      System.out.println("guesses : " + hangman.guessesLeft()); 
      if (DEBUG) { 
       System.out.println(hangman.words().size() + " words left: " 
         + hangman.words()); 
      } 
      System.out.println("guessed : " + hangman.guesses()); 
      System.out.println("current : " + hangman.pattern()); 
      System.out.print("Your guess? "); 
      char ch = console.next().toLowerCase().charAt(0); 
      if (hangman.guesses().contains(ch)) { 
       System.out.println("You already guessed that"); 
      } else { 
       int count = hangman.record(ch); 
       if (count == 0) { 
        System.out.println("Sorry, there are no " + ch + "'s"); 
       } else if (count == 1) { 
        System.out.println("Yes, there is one " + ch); 
       } else { 
        System.out.println("Yes, there are " + count + " " + ch 
          + "'s"); 
       } 
      } 
      System.out.println(); 
     } 
    } 

    // reports the results of the game, including showing the answer 
    public static void showResults(HangmanManager hangman) { 
     // if the game is over, the answer is the first word in the list 
     // of words, so we use an iterator to get it 
     String answer = hangman.words().iterator().next(); 
     System.out.println("answer = " + answer); 
     if (hangman.guessesLeft() > 0) { 
      System.out.println("You beat me"); 
     } else { 
      System.out.println("Sorry, you lose"); 
     } 
    } 

そして、私のような初心者を助ける時間をとってくれてありがとう。

+4

ます[検閲]。どのラインに例外がありますか?どのインデックスを使用しており、配列のサイズはどのくらいですか? – Simulant

+0

'ArrayIndexOutOfBoundsException'はあなたの配列に存在しないインデックスにアクセスしようとしています。そのような単純な。例えば。 'array" {"A"、 "B"、 "C"} 'これは長さ3の配列です。つまり、インデックス0,1,2にしかアクセスできません。このエラーが発生します。したがって、配列上に存在しないインデックスにアクセスしようとしている場所を特定する必要があります。 @Simulantによって与えられた助言に従うと、あなたは知るでしょう。 –

+1

'for(int i = 0; i> commonPattern.length(); i ++)'ループは決して実行されません。 –

答えて

-1

コンソールまたはデバッグファイルへの出力行です。そのため、コードのどこでディメンションが違反されているのかを正確に追跡したり、例外を処理したりできます(try catchで読み取る)。

これは、プログラムの一部である開発者ツールなしでデバッグを許可し、エンドユーザーがバグレポートを提出できるためです。この種の問題を認識することは、ユーザーがそれを認識することなく内部的に解決するコードを追加できることを意味します。これは内部的な解決策を必要とする比較的簡単な問題ですが、将来、システム、環境、またはユーザー固有の問題が発生する可能性があるため、早期に慣れるのが良い方法です。

これらは遭遇する厄介なバグですが、見つけたときに本当に簡単に解決できます。括弧を忘れるような感じです。見落としが簡単、追跡する、とあなたはスタックトレースを読むあなたがそれを見つけたとき、自分自身を平手打ち、あるいは少なくとも、それは私の経験です;-)

https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

+0

ようこそスタックオーバーフロー!より多くの質問に答える前に、[良い答えを書くにはどうすればいいですか?](http://stackoverflow.com/help/how-to-answer)をお読みください。 –

関連する問題