Question

In: Computer Science

Create a lottery game application. Include a menu that allows the user to play more than once, or quit after a game. You can either use dialog boxes or text based, up to you.

FOR JAVA:

Summary:

Create a lottery game application. Include a menu that allows the user to play more than once, or quit after a game. You can either use dialog boxes or text based, up to you.

  • The solution file should be named Lottery.java

  • Generate four random numbers, each between 0 and 9 (inclusive).

  • Allow the user to guess four numbers.

  • Compare each of the user’s guesses to the four random numbers and display a message that includes the user’s guess, the randomly determined four-digit number, and the amount of points the user has won as follows:

No matches0 points
Any one digit matching5 points
Any two digits matching100 points
Any three digits matching2,000 points
All four digits matching1,000,000 points
  • Run your program until it works and the output looks nice.

Solutions

Expert Solution

import java.util.Random;
import java.util.Scanner;

public class Lottery {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int total = 0, points, d1, d2, matched, generatedNumber;
        Random random = new Random();
        while (true) {
            System.out.println("Try to figure out lottery number");
            matched = 0;
            generatedNumber = 0;
            for (int i = 0; i < 4; i++) {
                System.out.print("Enter digit " + (i + 1) + ": ");
                d1 = in.nextInt();
                d2 = random.nextInt(10);
                generatedNumber *= 10;
                generatedNumber += d2;
                if (d1 == d2) {
                    ++matched;
                }
            }
            if (matched == 0) {
                points = 0;
            } else if (matched == 1) {
                points = 5;
            } else if (matched == 2) {
                points = 1000;
            } else if (matched == 3) {
                points = 2000;
            } else {
                points = 1000000;
            }
            System.out.println("Lottery number was " + generatedNumber);
            System.out.println("You won points " + points);
            total += points;
            System.out.print("Do you want to play again(y or n): ");
            char choice = in.next().charAt(0);
            if (choice == 'n')
                break;
            System.out.println();
        }
        System.out.println("\nTotal number of points won is " + total);
    }
}

Related Solutions

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT