溫馨提示×

java實(shí)現(xiàn)小游戲編程源代碼

小云
115
2023-09-22 02:20:32
欄目: 編程語言

這是一個(gè)簡單的猜數(shù)字游戲的 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();
}
}

這個(gè)游戲會在 1 到 100 之間生成一個(gè)隨機(jī)數(shù),然后玩家需要猜出這個(gè)數(shù)。程序會根據(jù)玩家的猜測給出相應(yīng)的提示,直到玩家猜中為止。最后會顯示玩家猜中的次數(shù)。

0