gpt4 book ai didi

Java 刽子手代码

转载 作者:行者123 更新时间:2023-12-01 13:35:18 25 4
gpt4 key购买 nike

我已经被这段代码困扰了一段时间,并且非常感谢一些帮助。所以基本上我的刽子手代码运行得很好,但是控制台中的显示(其中破折号应该反射(reflect)哪些字母已被正确猜测,哪些字母仍有待猜测)是完全错误的。我将在这里发布我的代码。由于篇幅较长,我只贴出相关方法。我觉得问题似乎出在显示数组列表上,我无法持续更新它。

     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;
}

最佳答案

问题是这一行:

lettersInWord.remove(index);当您调用此方法时,您正在移动数组列表,因此当您获取新索引时,它将是不正确的,因为它已被移动。例如,假设 secret 词是“测试”。首先,数组列表将为 [t,e,s,t],当您询问第一个 t 的索引时,您将得到 0(正确)。但在调用 arraylist.remove 之后,你将得到 [e.s.t]。当询问第二个 t 的索引时,它将返回 2 而不是您要查找的 3。

也许您应该有第二个数组列表,它可以完整地保存您将用于索引查找的 secret 单词,并保留第一个数组列表来存储剩余的字母。

关于Java 刽子手代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com