java实现小游戏编程源代码

1259
2023/9/11 2:20:32
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这是一个简单的猜数字游戏的 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 之间生成一个随机数,然后玩家需要猜出这个数。程序会根据玩家的猜测给出相应的提示,直到玩家猜中为止。最后会显示玩家猜中的次数。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中format的功能有哪些