如何随机生成猜测

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


我在弄清楚当有人输入“是”或“否”时如何执行代码时遇到问题。我应该做一个 do 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. 报告中奖号码、中奖彩票、总奖金、总损失以及允许扣除的金额


GCT1015
浏览 81回答 1
1回答

慕后森

一般来说,布尔值可以方便地控制这样的循环。就像是: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;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java