나는 학교에서 프로그래밍 수업을 듣기 위해 컴퓨터가 단어를 고르지 않는 사악한 행맨 게임을 만들기로되어있는 학교에서 프로젝트를 진행하고 있습니다. 사용자가 공정하게 게임한다고 생각하도록 속이기 위해 컴퓨터는 동일한 문자 패턴을 가진 단어 만 고려합니다.배열이 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");
}
}
그리고 나 같은 초보자를 도와 주셔서 감사합니다.
는 스택 트레이스를 읽기입니다. 어떤 라인에서 Exception을 얻습니까? 어떤 색인을 사용하고 배열에 어떤 크기가 있습니까? – Simulant
'ArrayIndexOutOfBoundsException'은 배열에없는 인덱스에 액세스하려는 것입니다. 그처럼 간단합니다. 예 : 'array "{"A ","B ","C "}'이것은 인덱스 0, 1 및 2에만 액세스 할 수 있다는 것을 의미하는 길이가 3 인 배열입니다. 배열에 대해 인덱스 3에 액세스하려고하면 이 오류가 발생합니다. 따라서 배열의 존재하지 않는 인덱스에 액세스하려는 위치를 파악해야합니다. @Simulant가 제공 한 조언을 따라하면 알게 될 것입니다. –
또한'for (int i = 0; i> commonPattern.length(); i ++)'루프는 결코 실행되지 않습니다. –