【问题标题】:Creating a class that generates and random number创建一个生成随机数的类
【发布时间】:2016-03-14 00:08:41
【问题描述】:

我的任务是从 1 和 10 中生成一个随机数,用户猜测该数字并根据过高或过低再次猜测。当数字被猜对时,它会显示它花了 X 次来猜它。与其让别人为我做这一切,不如给我一个解释,这样我将来可以帮助自己。我希望我已经展示了下面仍然需要做的事情。谢谢。

import java.security.SecureRandom;
import java.util.Scanner;

public class GuessTheNumber {
    private SecureRandom randomNumber = new SecureRandom();
    private Scanner input = new Scanner(System.in);
    private int numberOfGuesses;

    public void play() {
        int theNumber = 1 + randomNumber.nextInt(10);
        numberOfGuesses = 0;

        int guess = askForGuess();

        //see if their guess is correct, I know a Boolean is needed somewhere here. 
        //otherwise call askForGuess() again, also If and While statements. 

            System.out.printf("You guessed correctly in %d times%n", numberOfGuesses);
    }

    private int askForGuess() {
        numberOfGuesses++;
        int guess = 0;

        //ask for the guess
        //make sure the guess is valid

        return guess;
    }
}

import java.util.Scanner;

public class GuessTheNumberTest {

    public static void main(String [] args) {
        Scanner scanner = new Scanner(System.in);
        GuessTheNumber game = new GuessTheNumber();
        int playAgain;

        do {
            game.play();
            System.out.println("Play again? 1-yes, 0-no");
            playAgain = scanner.nextInt();
        } while(playAgain == 1);
    }

}

【问题讨论】:

    标签: java if-statement while-loop nested-loops


    【解决方案1】:

    您应该尝试接受用户的输入,直到用户输入与随机生成的数字匹配。还要不断增加 numberOfGuesses 的计数。当用户输入与随机数匹配时,返回猜测的次数并打印出来。 您可能正在寻找类似的东西:

    private int askForGuess(int theNumber) {
    
            int guessed = in.nextInt();
            numberOfGuesses = 1;
            while(guessed != thetheNumber )
            {
                guessed = in.nextInt();
                numberOfGuesses++;
            }
           return numberOfGuesses;
        }
    

    注意:您可能希望将 theNumber 变量设为全局变量或将 ti 传递给您的 askForGuess() 函数

    【讨论】:

    • 非常感谢。我试试看。
    猜你喜欢
    • 2023-01-03
    • 1970-01-01
    • 2013-01-03
    • 2011-09-18
    • 2018-04-21
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2012-06-09
    相关资源
    最近更新 更多