Answer to Question #257179 in Java | JSP | JSF for Flying Bird

Question #257179
Write a program that simulates a lottery. The program should have an array of five integers named lottery and should generate a random number in the range of 0 through 9 for each element in the array. The user should enter five digits, which should be stored in an integer array named user. The program is to compare the corresponding elements in the two arrays and keep a count of the digits that match. For example, the following shows the lottery array and the user array with sample numbers stored in each. There are two matching digits (elements 2 and 4). lottery array: 7 4 9 1 3 user array: 4 2 9 7 3 The program should display the random numbers stored in the lottery array and the number of matching digits. If all of the digits match, display a message proclaiming the user as a grand prize winner. Input Validation: Do not accept a negative value for lottery number. Also keep track of array size.
1
Expert's answer
2021-10-27T00:25:53-0400
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Random random = new Random();
        Scanner in = new Scanner(System.in);
        int[] lottery = new int[5];
        int[] user = new int[lottery.length];
        for (int i = 0; i < lottery.length; i++) {
            lottery[i] = random.nextInt(10);
        }
        for (int i = 0; i < user.length; i++) {
            do {
                System.out.print(i + 1 + ": ");
                user[i] = in.nextInt();
            } while (user[i] < 0);
        }
        StringBuilder matchingDigits = new StringBuilder();
        int count = 0;
        System.out.print("Lottery: ");
        for (int i = 0; i < lottery.length; i++) {
            System.out.print(lottery[i] + " ");
            if (lottery[i] == user[i]) {
                matchingDigits.append(i).append(" ");
                count++;
            }
        }
        System.out.println("\nThe number of matching digits: " + matchingDigits);
        if (count == lottery.length) {
            System.out.println("You are a grand prize winner!!!");
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS