当前位置: 代码迷 >> 综合 >> 第三章第十五题(游戏:彩票)(Game: lottery)
  详细解决方案

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

热度:76   发布时间:2024-02-26 09:43:05.0

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

  • **3.15(游戏:彩票)修改程序清单3-8,产生三位整数的彩票。程序提示用户输入一个三位整数,然后依照下面判定用户是否赢得奖金:
  1. 如果用户输入的所有数包括顺序完全匹配彩票数字,奖金是10000美元。

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

  3. 如果用户输入的其中一个数匹配彩票号码中的一个数,奖金是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:

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

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

  6. 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 numberfinal int lottery = (int)(Math.random() * 1000);// Prompt the user to enter a guessSystem.out.print("Enter your lottery pick (three digits): ");Scanner input = new Scanner(System.in);guess = input.nextInt();// Get digits from guessguessDigit1 = guess / 100;guessDigit2 = guess % 100 / 10;guessDigit3 = guess % 10;// Get digits from lotterylotteryDigit1 = lottery / 100;lotteryDigit2 = lottery % 100 / 10;lotteryDigit3 = lottery % 10;// Check the guessif(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 $1000Process finished with exit code 0
  相关解决方案