java - 如何获得随机生成的猜测
问题描述
我对 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 彩票游戏
解决方案
通常,布尔值可以方便地控制这样的循环。就像是:
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;
}
推荐阅读
- python - 是否可以在 Thonny 中运行特定的 Python 代码行而不是整个脚本?
- wxpython - 如何从内部面板触发 wx.EVT_CLOSE
- python - 为什么我得到一个 NameError 试图运行这个 For 循环
- excel - 当 ID = 某个值时,根据 ID 将两个值相加
- outlook - 自定义列 - 是否可转发?
- android - 有没有办法省略 layout_height 以使两个视图具有相同的高度?
- amazon-ec2 - Hazelcast 成功发现节点但无法连接(OrientDB)
- mysql - MySQL,mysqlbinlog加载错误后恢复数据库?
- python - 将所有单元格保持在 pandas DataFrame 中的给定值以上
- footer - 如何仅从 TCPDF 的第二页显示页数