简体   繁体   中英

Lottery program using arrays and methods (Java)

I am making a lottery program that simulates a person picking the 6 winning numbers and a draw of winning numbers using methods.

This is an example output

Enter your numbers:

25
31
20
8
47
31

The winning numbers are:
48 16 28 38 46 36

0 out of the 6 numbers you chose are winning numbers, better luck next time!

My problem is that the method for finding the number of total matched numbers is not working and I do not know how to fix it. The user input numbers and the lottery random numbers are both arrays

This is the code I have:

import java.util.*;

public class Main {

    private static boolean[] lottery;
    private static boolean[] array;

    public static void main(String[] args) {

        getUserNumbers();

        getRandomNumbers();

        getTotalMatchedNumbers();

}


    public static void getRandomNumbers(){

            int[] lottery = new int[6];
            int lotteryNumbers;
        
            for (int i = 0; i < 6; i++) {
                lotteryNumbers = (int) (Math.random() * 50);
                for (int x = 0; x < i; x++) {
                    if (lottery[x] == lotteryNumbers)
                    {
                        lotteryNumbers = (int) (Math.random() * 50);
                        x = -1;
                    }
        
                }
                lottery[i] = lotteryNumbers;
            }
            
            System.out.println("The winning numbers are: ");
            for (int i = 0; i < lottery.length; i++)
                System.out.print(lottery[i] + " ");
        
        }
    

    public static void getUserNumbers(){
        Scanner scanner = new Scanner(System.in);
         
            int[] array = new int[10];  
    
        System.out.println("Enter your numbers: "); 
    
        for(int i=0; i < 6; i++){  
      
            array[i]=scanner.nextInt();  
    
        }  

        System.out.println("You have entered: ");  

        for (int i=0; i < 6; i++){  
            System.out.print(array[i]);  
            System.out.print(" ");
            System.out.println(" ");
           
        }  
    }

    public static void getTotalMatchedNumbers(){

        int matched = 0;
        for(int i = 0; i < 6; i++){
            for(int j = 0;j < 6; j++){
                if(lottery[i] == array[j]){
                        matched = matched + 1;
                }
            }
            if (matched != 6){
                System.out.println(matched + " out of the 6 numbers you chose are winning numbers, better luck next time!");
            }
            else{
                System.out.println("You got picked all the winning numbers! You win!");
            }
        }

    }
}

It is better to provide functions that accept some arguments and return results instead of modifying some variables/fields outside the function because it helps to avoid many errors and facilitates testing of such functions.

Also, if the same number/value occur more than one time in the code, it is better to extract it into a separate constant to decrease the number of places in the code where the change may be necessary, for example, the code above contains 6 in all methods, thus if there's a need to change this definitely single parameter, a lot of places need to be updated.

So, the code could be enhanced like this:

// main method
final int NUM_COUNT = 6;
final int LOTTERY_SIZE = 12; // use small number for testing purpose

int[] userNums = getUserNumbers(NUM_COUNT, 1, LOTTERY_SIZE);
int[] lottery  = getLotteryNumbers(NUM_COUNT, 1, LOTTERY_SIZE);

System.out.print("The winning numbers are: ");
Arrays.stream(lottery).forEach(i -> System.out.print(i + " "));
System.out.println();

int win = getWinCount(lottery, userNums);

System.out.printf("%d out of %d numbers guessed.%n", win, NUM_COUNT);

if (win == NUM_COUNT) {
    System.out.println("You won the jackpot!");
}else {
    System.out.println("Better luck next time!");
}

Read numbers input by user and validate the user input.

public static int[] getUserNumbers(int numCount, int minNum, int maxNum) {
    int[] userNums = new int[numCount];
    Scanner input = new Scanner(System.in);
    System.out.printf("Input %d numbers between %d and %d%n", numCount, minNum, maxNum);
    for (int i = 0; i < numCount; i++) {
        userNums[i] = input.nextInt();
        if (userNums[i] < minNum || userNums[i] > maxNum) {
            System.out.println("Invalid number, please correct");
            i--;
        }
    }
    return userNums;
}

Generate lottery numbers using arrays and ensure no duplicate occurs, though it would be much more convenient to use Set in this case.

public static int[] getLotteryNumbers(int numCount, int minNum, int maxNum) {
    Random random = new Random();
    int[] lottery = new int[numCount];
    for (int i = 0; i < numCount; i++) {
        int n = minNum + random.nextInt(maxNum);
        boolean duplicate = false;
        for (int j = i - 1; j >= 0; j--) {
            if (lottery[j] == n) {
                duplicate = true; 
                break;
            }
        }
        if (!duplicate) {
            lottery[i] = n;
        } else {
            i--;
        }
    }
    return lottery;
}

Calculate the number of guessed numbers. It can also be facilitated using Set and method retainAll .

public static int getWinCount(int[] lottery, int[] user) {
    int win = 0;
    for (int i = 0; i < lottery.length; i++) {
        for (int j = 0; j < user.length; j++) {
            if (lottery[i] == user[j]) {
                win++;
                break;
            }
        }
    }
    return win;
}

Example output

Input 6 numbers between 1 and 12
2 3 6 7 10 11
The winning numbers are: 7 6 3 8 11 5 
4 out of 6 numbers guessed.
Better luck next time!

You should use fields in your numbers-related methods, because your numbers are generated in methods locally, not class-wise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM