第三章第十五题(游戏:彩票)(Game: lottery)

    科技2022-07-12  139

    第三章第十五题(游戏:彩票)(Game: lottery)

    **3.15(游戏:彩票)修改程序清单3-8,产生三位整数的彩票。程序提示用户输入一个三位整数,然后依照下面判定用户是否赢得奖金:

    如果用户输入的所有数包括顺序完全匹配彩票数字,奖金是10000美元。

    如果用户输入的所有数匹配彩票的所有数字,奖金是3000美元。

    如果用户输入的其中一个数匹配彩票号码中的一个数,奖金是1000美元。

    **3.15(Game: lottery) Revise Listing 3.8, Lottery.java, to generate a lottery of a three-digit number. The program prompts the user to enter a three-digit number and determines whether the user wins according to the following rules:

    If the user input matches the lottery number in the exact order, the award is $10,000.

    If all digits in the user input match all digits in the lottery number, the award is $3,000.

    If one digit in the user input matches a digit in the lottery number, the award is $1,000.

    参考代码: package chapter03; import java.util.Scanner; public class Code_15 { public static void main(String[] args) { int guess, guessDigit1, guessDigit2, guessDigit3; final int lotteryDigit1, lotteryDigit2, lotteryDigit3; // Generate a lottery number final int lottery = (int)(Math.random() * 1000); // Prompt the user to enter a guess System.out.print("Enter your lottery pick (three digits): "); Scanner input = new Scanner(System.in); guess = input.nextInt(); // Get digits from guess guessDigit1 = guess / 100; guessDigit2 = guess % 100 / 10; guessDigit3 = guess % 10; // Get digits from lottery lotteryDigit1 = lottery / 100; lotteryDigit2 = lottery % 100 / 10; lotteryDigit3 = lottery % 10; // Check the guess if(lottery == guess) System.out.println("Exact match:you win $10000"); else if((lotteryDigit1 == guessDigit1 && lotteryDigit2 == guessDigit3 && lotteryDigit3 == guessDigit2) ||(lotteryDigit1 == guessDigit2 && lotteryDigit2 == guessDigit1 && lotteryDigit3 == guessDigit3) ||(lotteryDigit1 == guessDigit2 && lotteryDigit2 == guessDigit3 && lotteryDigit3 == guessDigit1) ||(lotteryDigit1 == guessDigit3 && lotteryDigit2 == guessDigit1 && lotteryDigit3 == guessDigit2) ||(lotteryDigit1 == guessDigit3 && lotteryDigit2 == guessDigit2 && lotteryDigit3 == guessDigit1)) { System.out.println("Match all digits:you win $3000"); } else if(lotteryDigit1 == guessDigit1 || lotteryDigit1 == guessDigit2 || lotteryDigit1 == guessDigit3 ||lotteryDigit2 == guessDigit1 || lotteryDigit2 == guessDigit2 || lotteryDigit2 == guessDigit3 ||lotteryDigit3 == guessDigit1 || lotteryDigit3 == guessDigit2 || lotteryDigit3 == guessDigit3) { System.out.println("Match one digit:you win $1000"); } else { System.out.println("Sorry,no match"); } input.close(); } } 结果显示: Enter your lottery pick (three digits): 698 Match one digit:you win $1000 Process finished with exit code 0
    Processed: 0.015, SQL: 8