我已经坚持使用这段代码一段时间了,非常感谢一些帮助。所以基本上我的hangman代码运行正常,但是控制台中的显示,其中破折号应该反映哪些字母已被正确猜测,以及哪些字母仍有待猜测是完全错误的。我会在这里发布我的代码。由于时间很长,我只会发布相关方法。我觉得问题就在于显示器阵列列表,我无法持续更新。
public void play() {
String SecretWord = getWord();
ArrayList <String> lettersInWord = new ArrayList <String>();
for (int i=0;i<SecretWord.length();i++){
lettersInWord.add(Character.toString(SecretWord.charAt(i)));
}
int remainingChances = getNumberGuesses();
int noOfLetters = SecretWord.length();
ArrayList<String> lowerCaseAlphabets = getAlphabetArrayList();
ArrayList<String> display = new ArrayList<String>();
for (int i = 0; i<noOfLetters; i++) {
display.add("_");
}
System.out.println(printDisplay(display));
Set <String> lettersGuessed = new HashSet<String>();
while (remainingChances > 0){
String question = readString("What letter do you want to guess?");
if (lowerCaseAlphabets.contains(question)){
System.out.println("Number of misses remaining equals "+remainingChances+"");
int index = lettersInWord.indexOf(question);
if (index== -1){
lettersGuessed.add(question);
remainingChances-= 1;
if (remainingChances==0){
System.out.println("No "+question+". You lose! The secret word was "+SecretWord+"");
}
else if (remainingChances>0){
System.out.println("There is no "+question+" in the word");
System.out.println(printDisplay(display));
System.out.println("Guesses so Far :"+lettersGuessed+"");
}
}
else if (index!=-1){
while (index!= -1){
display.set(index, question);
System.out.println(printDisplay(display));
System.out.println("Guesses so Far :"+lettersGuessed+"");
lettersInWord.remove(index);
if (lettersInWord.size()==0){
System.out.println("You have won! Congratulations!");
return;
}
else if (lettersInWord.size()!=0){
index = lettersInWord.indexOf(question);
}
}
}
}
else {
System.out.println("The letter you have chosen in invalid. You must pick a lower case letter from the alphabet!");
}
}
}
public String printDisplay(ArrayList<String> display){
String View = "";
for (int i =0;i<display.size();i++){
View+= display.get(i) + " ";
}
return View;
}
答案 0 :(得分:1)
问题是这一行:
lettersInWord.remove(index);
当你调用它时,你正在移动arraylist,这样当你获得新索引时,它将是不正确的,因为它已被移动。例如,让我们说秘密词是“测试”。首先,arraylist将是[t,e,s,t],当你要求第一个t的索引时,你将得到0(正确)。但是在调用arraylist.remove之后你会有[e.s.t]。当询问第二个t的索引时,它将返回2而不是你要找的3个。
也许你应该有一个第二个arraylist,保持秘密单词完整,你将用于索引查找,并保留第一个存储其余字母。