java实现小游戏编程源代码
这是一个简单的猜数字游戏的 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 之间生成一个随机数,然后玩家需要猜出这个数。程序会根据玩家的猜测给出相应的提示,直到玩家猜中为止。最后会显示玩家猜中的次数。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:美国服务器拥有多个IP的作用有哪些 下一篇:Aconvert在线转化工具如何使用
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。