📜  Java的数字猜谜游戏

📅  最后修改于: 2021-05-04 20:23:38             🧑  作者: Mango

任务是编写一个Java程序,在该程序中,用户将进行K次试验以猜测一个随机生成的数字。以下是游戏规则:

  • 如果猜中的数字大于实际数字,则程序将以以下消息响应:猜中的数字大于实际数字。
  • 如果猜中的数字小于实际数字,则程序将以以下消息响应:猜中的数字小于实际数字。
  • 如果猜中的数字等于实际数字,或者如果用尽了K次尝试,程序将以一条适当的消息结束。

方法:以下是步骤:

  • 该方法是使用Java的Math.random()方法生成一个随机数。
  • 现在使用循环,从用户那里获取K个输入,并且对于每个输入打印,无论该数字是小于还是大于实际数字。
  • 如果在K次尝试中用户正确猜中了该数字,请打印出该用户获胜的信息。
  • 否则,他无法猜测,然后打印出实际数字。

下面是上述方法的实现:

Java
// Java program for the above approach
import java.util.Scanner;
  
public class GFG {
  
    // Function that implements the
    // number guessing game
    public static void
    guessingNumberGame()
    {
        // Scanner Class
        Scanner sc = new Scanner(System.in);
  
        // Generate the numbers
        int number = 1 + (int)(100
                               * Math.random());
  
        // Given K trials
        int K = 5;
  
        int i, guess;
  
        System.out.println(
            "A number is chosen"
            + " between 1 to 100."
            + "Guess the number"
            + " within 5 trials.");
  
        // Interate over K Trials
        for (i = 0; i < K; i++) {
  
            System.out.println(
                "Guess the number:");
  
            // Take input for guessing
            guess = sc.nextInt();
  
            // If the number is guessed
            if (number == guess) {
                System.out.println(
                    "Congratulations!"
                    + " You guessed the number.");
                break;
            }
            else if (number > guess
                     && i != K - 1) {
                System.out.println(
                    "The number is "
                    + "greater than " + guess);
            }
            else if (number < guess
                     && i != K - 1) {
                System.out.println(
                    "The number is"
                    + " less than " + guess);
            }
        }
  
        if (i == K) {
            System.out.println(
                "You have exhausted"
                + " K trials.");
  
            System.out.println(
                "The number was " + number);
        }
    }
  
    // Driver Code
    public static void
    main(String arg[])
    {
  
        // Function Call
        guessingNumberGame();
    }
}


输出:
以下是上述程序的输出: