java - 使用循环计算剩余的尝试次数
问题描述
我有这个名人猜谜游戏,用户必须猜测名人的名字,只给出名字中的一部分字母。我给玩家“线索”(egrge oney)并阅读他们的猜测。程序应该有一个循环,让他们继续猜测。如果他们猜错了 3 次,给他们一个提示 如果他们第四次猜错了(在提示之后),他们就输了(你应该告诉他们名人是谁)。
我的循环有问题。这就是我到目前为止所拥有的。
System.out.println("Celebrity Guessing Game");
String celeb = "John Lennon";
System.out.print("Choose your difficulty (easy/medium/hard): ");
String difficulty = input.nextLine();
int maxtry = 3;
if (difficulty.equals("easy"))
{
System.out.println("Here is your clue: " + celeb.substring(1, 4) + " " + celeb.substring(5,10));
}
else if (difficulty.equals("medium"))
{
System.out.println(("Here is your clue: " + celeb.substring(0, 3) + " " + celeb.substring(4,9)));
}
else if (difficulty.equals("hard"))
{
System.out.println(("Here is your clue: " + celeb.substring(2, 4) + " " + celeb.substring(5,7)));
}
System.out.print("What is your guess? ");
String guess1 = input.nextLine();
System.out.println("guess1 = " + guess1 + " celeb = " + celeb );
while (!guess1.equals(celeb) && maxtry == 3 ) {
if (!guess1.equals(celeb) && maxtry == 3) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
if (guess1.equals(celeb) || guess1.equals("john lennon")) {
System.out.println("Good Guess, you are correct!");
}
这是我的输出:
名人猜谜游戏
选择你的难度(简单/中等/困难):简单
这是你的线索:ohn Lenno
你的猜测是什么?约翰列侬
猜测1 =约翰列侬名人=约翰列侬
再试一次。剩下的猜测数:2
好猜,你是对的!
^ 为什么要通过两个 if 语句?
解决方案
问题在于检查条件。它有以下问题:
- 它应该
maxtry > 0
代替maxtry == 3
- 而不是
equals()
使用equalsIgnoreCase()
以下是更正的代码片段:
while (!guess1.equalsIgnoreCase(celeb) && maxtry > 0 ) {
if (!guess1.equalsIgnoreCase(celeb) && maxtry > 0) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
注意:您没有为其他尝试读取用户的输入。
推荐阅读
- php - 如何在 PHP 中将 HTML 页面转换为 PDF?
- python - 来自 David Hallac 的 Time Varying Graphical Lasso 中 Python 代码的多个问题
- python - upickling 错误数据被截断 - 保存大型数据帧的更好方法
- flutter - Flutter TabBar 剪切
- c# - 检查一个单词是否可以通过数组中的定义部分构建
- r - 通过迭代 for 循环创建单个图,将图拼凑在一起
- php - 为什么我在 PHPmailer 中出现签名错误:错误:02001002
- javascript - 部分重叠过渡动画
- flutter - Flutter - 检查是否出现 TextFormField 错误文本的小部件测试结果不一致
- python - 如何在 python/pandas 的 csv 文件中用前面的值填充后续的空值?