2017-05-03 1 views
1

나는 학교에서 프로그래밍 수업을 듣기 위해 컴퓨터가 단어를 고르지 않는 사악한 행맨 게임을 만들기로되어있는 학교에서 프로젝트를 진행하고 있습니다. 사용자가 공정하게 게임한다고 생각하도록 속이기 위해 컴퓨터는 동일한 문자 패턴을 가진 단어 만 고려합니다.배열이 ArrayIndexOutOfBoundsException을 가져 오는 이유는 무엇입니까?

글자 "a"와 "e"를 추측 한 다음에 배열에 ArrayIndexOutOfBoundsException이 있고 지난 몇 시간 동안 디버거를 사용하여 계산하려고했지만 여전히 문제가 보이지 않으며 전체 수업이 첫 글자로 작동하지만 두 번째 글자는 깨지니까요. 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

는 스택 트레이스를 읽기입니다. 어떤 라인에서 Exception을 얻습니까? 어떤 색인을 사용하고 배열에 어떤 크기가 있습니까? – Simulant

+0

'ArrayIndexOutOfBoundsException'은 배열에없는 인덱스에 액세스하려는 것입니다. 그처럼 간단합니다. 예 : 'array "{"A ","B ","C "}'이것은 인덱스 0, 1 및 2에만 액세스 할 수 있다는 것을 의미하는 길이가 3 인 배열입니다. 배열에 대해 인덱스 3에 액세스하려고하면 이 오류가 발생합니다. 따라서 배열의 존재하지 않는 인덱스에 액세스하려는 위치를 파악해야합니다. @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)를 읽으십시오. –

관련 문제