Java 循环练习小游戏的示例代码


以下是一个 Java 循环练习小游戏的示例代码。这个游戏要求玩家猜一个随机数,直到猜中为止。每次猜测后,程序会告诉玩家猜的数是太大了还是太小了,以帮助玩家调整猜测策略。

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

public class GuessingGame {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();

        int numberToGuess = rand.nextInt(100) + 1;
        int numberOfTries = 0;
        boolean win = false;

        System.out.println("I am thinking of a number between 1 and 100.");

        while (numberOfTries < 10) {
            System.out.print("Guess a number: ");
            int guess = input.nextInt();
            numberOfTries++;

            if (guess == numberToGuess) {
                win = true;
                break;
            } else if (guess < numberToGuess) {
                System.out.println("Your guess is too low.");
            } else {
                System.out.println("Your guess is too high.");
            }
        }

        if (win) {
            System.out.println("Congratulations, you win!");
            System.out.println("You took " + numberOfTries + " tries to guess the number.");
        } else {
            System.out.println("Sorry, you lose. The number I was thinking of was " + numberToGuess + ".");
        }
    }
}

这个程序使用了 java.util.Random 类来生成一个随机数,并使用 java.util.Scanner 类来读取玩家的输入。程序使用一个 while 循环来不断询问玩家的猜测,直到玩家猜中或猜测次数超过了限制。如果玩家猜中了,程序会输出一条祝贺信息并显示玩家猜中的次数。如果玩家没有猜中,程序会输出一条失败信息,并显示正确答案。


原文链接:codingdict.net