首页 > 解决方案 > 使用循环计算剩余的尝试次数

问题描述

我有这个名人猜谜游戏,用户必须猜测名人的名字,只给出名字中的一部分字母。我给玩家“线索”(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 语句?

标签: javaloops

解决方案


问题在于检查条件。它有以下问题:

  • 它应该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);
} 

注意:您没有为其他尝试读取用户的输入。


推荐阅读