我對 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. 報告中獎號碼、中獎彩票、總獎金、總損失以及允許扣除的金額
1 回答

慕后森
TA貢獻1802條經驗 獲得超5個贊
一般來說,布爾值可以方便地控制這樣的循環。就像是:
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;
}
添加回答
舉報
0/150
提交
取消