JAVA小游戏代码
时间: 2023-07-02 09:06:49 浏览: 76
这里提供一个简单的Java小游戏代码,是一个猜数字游戏,玩家需要猜测程序生成的随机数。
```java
import java.util.Scanner;
import java.util.Random;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
int secretNumber = random.nextInt(100) + 1;
int guess = 0;
int numGuesses = 0;
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.println("Can you guess what it is?");
while (guess != secretNumber) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
numGuesses++;
if (guess < secretNumber) {
System.out.println("Too low! Guess again.");
} else if (guess > secretNumber) {
System.out.println("Too high! Guess again.");
} else {
System.out.println("Congratulations, you guessed the number!");
System.out.println("It took you " + numGuesses + " guesses.");
}
}
}
}
```
这个程序生成一个1到100之间的随机数,然后让玩家猜测这个数字。如果玩家猜的数字比随机数小,则程序会提示“太低了!再猜一次。”,如果猜的数字比随机数大,则程序会提示“太高了!再猜一次。”,直到玩家猜中这个数字为止。程序会输出玩家猜中这个数字所用的次数。
阅读全文