这是一个简单的猜数字游戏的 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数组如何移除元素