Java 中的猜数字游戏

10 Sept 2024 | 4 分钟阅读

在 Java 中,一个数字猜谜游戏是一个基本的入门级游戏,在这个游戏中,计算机生成一个随机数,玩家在一个特定的范围内尝试猜测它。下面是对其工作原理的简要介绍。

  • 游戏开始时,计算机会在给定的范围内(例如,1 到 100 之间)生成一个随机数。
  • 玩家猜测下一个数字:系统要求参与者输入他们对随机数的最佳猜测。
  • 比较以下猜测:然后,计算机将玩家的猜测与随机生成的数字进行比较。
  • 提供输入:计算机根据比较向玩家提供反馈。它可以指示猜测是过高还是过低,或者猜测是否正确。
  • 重复或结束:玩家会一直猜测,直到他们猜中正确的数字,此时游戏将以庆祝信息结束。

游戏规则

创建一项 Java 程序,让用户有 K 次机会正确猜测一个随机生成的数字。游戏规则如下:

  • 如果猜测的数字大于实际数字,程序将回答说猜测的数字大于实际数字。
  • 如果猜测的数字小于实际数字,程序将回答说猜测的数字小于实际数字。
  • 如果猜测正确或 K 次机会都已用完,程序将以适当的消息终止。

方法

  • 方法是使用 Math.random() 函数在 Java 中生成一个随机整数。
  • 现在,使用循环,接受用户 K 次输入,并针对每次输入发布猜测的数字是低于还是高于实际数字。
  • 如果在 K 次尝试内,用户猜对了数字,则报告用户获胜。
  • 否则,发布他未能猜中,并附上实际数字。

数字猜谜游戏 Java 程序

NumberGuess.java

输出

Welcome to the Number Guessing Game!
A number has been chosen between 1 and 100.
Your task is to guess the number within 5 attempts.
Attempt 1: Enter your guess:
3
The secret number is greater than your guess.
Attempt 2: Enter your guess:
50
The secret number is less than your guess.
Attempt 3: Enter your guess:
30
The secret number is less than your guess.
Attempt 4: Enter your guess:
20
The secret number is greater than your guess.
Attempt 5: Enter your guess:
24
You have exhausted all 5 attempts.
The secret number was 29

让我们来看另一种相同的方法。

NumberGuess.java

输出

I'm thinking of a number between 1 and 100.
You have 5 attempts to guess the number.
Enter your guess: 
5
Your guess is too low. You have 4 attempts left.
Enter your guess: 
25
Your guess is too low. You have 3 attempts left.
Enter your guess: 
50
Your guess is too low. You have 2 attempts left.
Enter your guess: 
70
Your guess is too low. You have 1 attempts left.
Enter your guess: 
90
Your guess is too high. You have 0 attempts left.
You've run out of attempts. You lose!