2

我正在用 Java 编写一个传统的刽子手游戏。我目前坚持的是查找用户输入的字符是否不是String.

if(getLetters.indexOf(userCharInput)==-1) //getLetters is the StringBuilder, and the userCharInput is a String.
{
     playerCounter++;
}

这是我似乎遇到麻烦的部分,我查看了不同的indexOf示例,并将其制定为与我的程序一起使用。

问题是,它不起作用。我将它设置为让玩家有 3 次猜测单词的机会,因为默认单词是“apple”,我猜的是 'a'、'p' 和 'l',剩下的 'e' 有待猜测。现在我故意做出 3 个错误的猜测,但它不会触发下一个else if

else if(playerCounter == 3)
{
    System.out.println("All lives are gone! Game Over!");
    playerCounter = 1; //resets the playerCounter to one.
    System.exit(0);
}

任何帮助将不胜感激。

4

4 回答 4

3

这是因为当你不断猜错字母时,第一个if语句被评估为真:

if(getLetters.indexOf(userCharInput)==-1) //getLetters is the StringBuilder, and the userCharInput is a String.
{
     playerCounter++;
}

So you keep increasing playerCounter (beyond 3). This means that your next statement is unreachable (once it's greater than 3, it's not going to get any smaller, at least with the code you have posted so far). So else if (playerCounter == 3) may not be reachable.

于 2012-12-31T22:58:41.143 回答
1

我猜你else if是另一个 if 语句的一部分,它正在变得真实,所以检查一下。

于 2012-12-31T22:52:33.970 回答
0

The reason it was not working was because of the indexOf method being used improperly,it was partially because of the ordering of the if statements, but that was very miniscule to the primary issue. What had to be changed was the way I used the indexOf method.

ie. instead of gletter.indexOf(character); it should have been word.indexOf(character); where word was the word that had to be guessed, and gletter was the StringBuilder used to keep track of user guesses.

于 2013-01-01T02:53:17.523 回答
-2

这是 StringBuilder 的 Javadoc:

根据您发布的代码,我猜:

1) 您将所需的字母(例如单词“apple”中的字母)保存到 getLetters。

2) getLetters 是 StringBuilder 类型

3) 如果 userCharInput 是“char”类型,那么 indexOf() 可能不会给出预期的结果

4) 用“if”代替“else if”

建议:

尝试将“getLetters”更改为“String”,看看是否有帮助。

while (...) {
  ...
  //getLetters is the StringBuilder, and the userCharInput is a String.
  if(getLetters.indexOf(userCharInput)==-1)  {
     playerCounter++;
  }
  // Debug: comment this out once it's working
  System.out.println ("userCharInput=" + userCharInput + ", playerCounter=" + playerCounter);
  if(playerCounter == 3) {
    System.out.println("All lives are gone! Game Over!");
    playerCounter = 1; //resets the playerCounter to one.
    System.exit(0);
  }
  ...
}
于 2012-12-31T22:56:16.053 回答