import java.util.Scanner;
import java.util.Random;

public class GuessNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Random rand = new Random();
        int number = rand.nextInt(100) + 1;
        int guess = 0;
        System.out.println("猜一个 1 到 100 之间的数字:");
        while (guess != number) {
            System.out.print("输入你的猜测:");
            guess = sc.nextInt();
            if (guess < number) {
                System.out.println("太小了,再试试");
            } else if (guess > number) {
                System.out.println("太大了,再试试");
            } else {
                System.out.println("恭喜你猜对了!");
            }
        }
    }
}

该代码使用 java.util.Scanner 类来读取用户的输入,并使用 java.util.Random 类生成随机数。游戏通过不断地提示用户输入猜测,直到他们猜中正确的数字为止。

最后修改:2023 年 02 月 09 日
如果觉得我的文章对你有用,请随意赞赏