用Java编写一个游戏程序
时间: 2024-04-30 22:19:19 浏览: 150
好的,我可以为您提供一个简单的Java游戏程序示例,这个游戏是猜数字游戏。
首先,让我们定义一个名为“GuessNumber”的类:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
private int numberToGuess;
private int numberOfGuesses;
public void play() {
Random rand = new Random();
numberToGuess = rand.nextInt(100) + 1;
numberOfGuesses = 0;
System.out.println("I'm thinking of a number between 1 and 100. Can you guess it?");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
numberOfGuesses++;
if (guess == numberToGuess) {
System.out.println("Congratulations! You guessed the number in " + numberOfGuesses + " guesses.");
break;
} else if (guess < numberToGuess) {
System.out.println("Too low. Try again.");
} else {
System.out.println("Too high. Try again.");
}
}
}
public static void main(String[] args) {
GuessNumber game = new GuessNumber();
game.play();
}
}
```
在这个程序中,我们使用了Java内置的Random类来生成一个随机数,然后使用Scanner类来获取用户的输入。在while循环中,我们比较用户的猜测和随机数的大小,然后给出相应的提示,直到用户猜中为止。
您可以将此代码复制到您的Java集成开发环境(IDE)中,并运行它,以查看该游戏是如何工作的。
阅读全文