這是一個簡單的猜數字游戲的 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 之間生成一個隨機數,然后玩家需要猜出這個數。程序會根據玩家的猜測給出相應的提示,直到玩家猜中為止。最后會顯示玩家猜中的次數。