Java高低猜测游戏循环错误

时间:2018-07-08 20:20:30

标签: java

我刚刚开始学习编程,并且正在通过Java进行入门。我正在使用循环和条件对一个猜谜游戏进行编程的常见编码练习。我的程序需要执行以下操作:

  1. 选择1到100之间的随机数
  2. 反复提示用户猜数字
  3. 向用户报告他或她是正确的或猜测很高 或每次猜测后低
  4. 为用户提供退出游戏中期的选项
  5. 计算游戏中的猜测次数,并在正确猜测时报告该次数
  6. 询问用户是否想在游戏成功后再次玩

到目前为止,我对循环语法有点不满意,需要我的程序提供一些帮助,因为存在很多我不知道如何解决的问题。有人会友好地帮我吗?请原谅许多可能显而易见的错误。


导入java.util.Scanner;

import java.util.Random;

猜猜公共课

{

public static void main(字符串[] args)

{

    final int MAX = 100;
    int answer, guess = 0, count = 0;
    String another = "y";

    Random generator = new Random();
    answer = generator.nextInt(MAX) + 1;

    Scanner scan = new Scanner(System.in);

    System.out.println("I'm thinking of a number between 1 and " + MAX
                        + ". Guess what it is: ");
    guess = scan.nextInt();

    while (another.equalsIgnoreCase("y"))
    {         
        while (guess != answer)
        {

            while (guess > MAX || guess < 1)
            {
                System.out.println("Invalid input. Please re-enter a number"
                + " between 1 and " + MAX + ":");
                guess = scan.nextInt();
            }

            if (guess == answer)
            {      
            count++;
            System.out.println("You guessed correctly!");
            }
            else if (guess > answer)
            {
                count++;
                System.out.println("You guessed too high. Guess again? Y/N:");
                another = scan.nextLine();
            }
            else if (guess < answer)
            {
                count++;
                System.out.println("You guessed too low. Guess again? Y/N:");
                another = scan.nextLine();
            }
        }
    }

    System.out.println("It took you " + count + "guess(es) to win.");
    System.out.println("Do you wish to play again? Y/N:?");
    another = scan.nextLine();
    count = 0;
    answer  = generator.nextInt(MAX) + 1;
}

}

1 个答案:

答案 0 :(得分:0)

一个问题是,您不会让用户在游戏中途退出,因为即使用户猜到了1到100范围内的数字并且没有得到正确的答案,他或她对{{1 }}将不会被检查,因为它所在的当前循环只会将Guess again: Y/N:guess进行比较,而不会比较answer。因此,在这种情况下,您最终将陷入无限循环,因为如果用户在答案为50时猜测为57,那么您将不断提示用户是否要再次猜测。

我的建议是删除第二个while循环

another

并将该循环内的代码放入while循环外

while (guess != answer)
{
    //other stuff
}

如果您希望用户能够再次播放,我建议您将前面的这段代码放在if语句中,以检查用户是否猜对了

while(another.equalsIgnoreCase("y")){
    //other stuff
}

这样,如果用户赢得游戏,将在while循环中检查他们选择再次玩游戏。我建议的最后一件事是移动此行

if (guess == answer)
{      
    count++;
    System.out.println("You guessed correctly!");
    System.out.println("It took you " + count + "guess(es) to win.");
    System.out.println("Do you wish to play again? Y/N:?");
    another = scan.nextLine();
    count = 0;
    answer  = generator.nextInt(MAX) + 1;
}

在检查guess = scan.nextInt(); 的while循环内,以便如果用户想再次玩游戏,游戏将提示用户进行猜测。