Java制作刽子手游戏
我在做绞刑游戏时遇到了一个小问题。我曾经就一个不同的错误发表过一篇帖子,但现在我遇到了一个我无法理解的新错误。我正试图验证guess这封信是否还没有输入。但是它跳过了if/else语句的整个部分。当我运行此代码时: 公共类测试工具{Java制作刽子手游戏,java,loops,Java,Loops,我在做绞刑游戏时遇到了一个小问题。我曾经就一个不同的错误发表过一篇帖子,但现在我遇到了一个我无法理解的新错误。我正试图验证guess这封信是否还没有输入。但是它跳过了if/else语句的整个部分。当我运行此代码时: 公共类测试工具{ static StringBuffer randomWord; static Scanner console = new Scanner(System.in); static int totalTries = 1; static String guess; stat
static StringBuffer randomWord;
static Scanner console = new Scanner(System.in);
static int totalTries = 1;
static String guess;
static char finalGuess;
public static void main(String[] args) throws Exception {
randomWord = TestingStuff.sendGet();
char[] guesses = new char[26];
int length = randomWord.length();
System.out.print("* * * * * * * * * * * * * * *"
+ "\n* Welcome to Hangman! *"
+ "\n* * * * * * * * * * * * * * *");
System.out.println("\nYou get 10 tries to guess the word by entering in letters!\n");
System.out.println(randomWord);
/*
Cycles through the array based on tries to find letter
*/
while (totalTries <= 10) {
System.out.print("Try #" + totalTries + "\nWord: " + makeDashes(randomWord));
//Right here: Search through the array of guesses, make it 26 characters to represent the alphabet
//if the user guess equals an already guessed letter, add to try counter. If it's correct, then reveal the letter that is
//correct and do it again without adding to the try counter.
System.out.print("\nWhat is your guess? ");
guess = console.nextLine();
finalGuess = guess.charAt(0);
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (guesses[i] != finalGuess) {
System.out.println(guesses[i]);
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess == randomWord.charAt(j)) {
//put a method that swaps out dashes with the guessed letter
totalTries++;
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
}
}
这只是说当数组中有一个空元素时,已经猜到了字母。我在这里遗漏了什么吗?是的。变量
totaltrys
最初是1。您读取猜测,然后将猜测[totaltrys-1]
设置为猜到的字符,意思是猜测[0]
等于finalGuess
。然后将i
从0循环到totaltrys-1
,该值也是0。循环执行一次,并检查第一个条目是否为finalGuess
。但确实如此,我们只是设置了它
如果使用for循环只是为了发现重复的猜测,那么可以将第一个for循环中的条件更改为
i
,这样应该可以工作,但需要移动标记下面的hangman单词。为了使对代码的影响降到最低,请使用m0skit0的解决方案。让我们用您的示例来浏览代码(我强烈建议您自己使用调试器执行此操作):
你可以走了
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array
在最外层的
for
循环的末尾。在处理猜测之前,不需要存储猜测。如果(猜测[i]!=finalGuess){}否则{“字母已经猜到了,再试一次!”
非常清楚。如果要控制“空”(什么是空的?)元素,然后您必须为它添加一个条件。@m0skit0当我提示用户输入猜测时,我有了它,它将把它放入字符值数组。这不是我在这里做的吗?我认为您的修复不起作用,因为问题发生在第一次迭代,而不是最后一次。@m0skit0啊,您是对的,我没有注意到he不仅检查重复猜测,而且在for循环中进行替换。在这种情况下,您的解决方案更好。我将编辑我的解决方案以更好地反映我的思路。
guesses[totalTries - 1] = finalGuess; // guesses[0] = 'a'
if (guesses[i] != finalGuess) // i = 0, guesses[0] = 'a', finalGuess = 'a'
else System.out.println("Letter already guessed, try again! ");
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array