我正在用 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);
}
任何帮助将不胜感激。
最佳答案
这是因为当你一直猜错字母时,第一个 if
语句的计算结果为 true:
if(getLetters.indexOf(userCharInput)==-1) //getLetters is the StringBuilder, and the userCharInput is a String.
{
playerCounter++;
}
所以你不断增加playerCounter(超过3)。这意味着您的下一条语句无法访问(一旦它大于 3,它就不会变得更小,至少对于您迄今为止发布的代码而言)。因此 else if (playerCounter == 3)
可能无法访问。
关于Java StringBuilder 与indexOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14106622/