首页 > 解决方案 > 如何获得随机生成的猜测

问题描述

我对 Java 还有些陌生,并且有一个实验室需要模拟一个生成 1-10 之间数字的彩票游戏。它首先询问用户他们想购买多少张彩票,然后询问他们是否希望计算机为他们生成猜测,如果是,那么它将生成猜测并显示中奖号码。如果用户说不,那么用户将自己输入猜测并显示中奖号码。

我在弄清楚当有人输入是或否时如何处理代码时遇到问题。我应该做一个while循环吗?

这是我现在拥有的代码。

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);


    double TICKET_PRICE = 2.00;

    System.out.println("Welcome to the State of Florida Play10 Lottery Game. Ticket Price: $" + TICKET_PRICE);

    System.out.println("How many tickets would you like to purchase?");
    int ticketsPurchased = input.nextInt();

    System.out.print("Please enter " + (ticketsPurchased) + " to confirm your credit carde charge: ");
    int creditCardCharge = input.nextInt();

    if (ticketsPurchased != creditCardCharge) {
        System.out.println("Wrong number, please enter again: ");
        return;
    }
    if (ticketsPurchased == creditCardCharge) {
        System.out.println("Thank you. Your credit card will be charged $" + (ticketsPurchased * 2));
    }
    int min = 1;
    int max = 10;
    int winner;
    winner = min + (int)(Math.random() * ((max - min) + 1));



    System.out.print("Would you like the computer to generate your guesses? Enter 'Y' or 'N': ");
    String computerGeneratedGuess = input.nextLine();

    int guess = 0;
    int winCtr = 0;
    String output = "";
}

算法如下: 1. 获取购票数量,计算并确认信用卡收费。2. 生成随机中奖整数并生成随机猜测或提示用户猜测。3. 报告中奖号码、中奖彩票、总中奖、总损失和允许扣除额

这是实验室本身: Lab05 彩票游戏

标签: java

解决方案


通常,布尔值可以方便地控制这样的循环。就像是:

boolean gameOver = false;
int theGuess = 0;
while (!gameOver) {
    if (computerGeneratedGuess == 'Y') {
        theGuess = //code to generate a random number
    }
    else {
        theGuess = //code to for user to enter a guess
    }
    if (theGuess == winner) {
        gameOver = true;
}

推荐阅读