这是一个简单的猜数字游戏的 Java 源代码:
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int secretNumber = (int) (Math.random() * 100);
int guess = 0;
int attempts = 0;
System.out.println("Welcome to the guessing game!");
System.out.println("I'm thinking of a number between 1 and 100.");
while (guess != secretNumber) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("Too low. Try again.");
} else if (guess > secretNumber) {
System.out.println("Too high. Try again.");
} else {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
}
}
input.close();
}
}
这个游戏会在 1 到 100 之间生成一个随机数,然后玩家需要猜出这个数。程序会根据玩家的猜测给出相应的提示,直到玩家猜中为止。最后会显示玩家猜中的次数。