简体   繁体   中英

Java Lottery Program Random Number Program

My code below is supposed to take the amount of tickets entered by the user and generate 6 random numbers for each ticket from number 1-49 and then check whether each number is equal or not. This is the output for example when the user enters 6 tickets. [I@38af3868 [I@77459877 [I@5b2133b1 [I@72ea2f77 [I@33c7353a [I@681a9515

My issue is why are there random letters and symbols with the numbers and why are the numbers generated the same everytime when they are supposed to be different and randomized.

Please guide me or fix my code! Thanks!

Scanner entry=new Scanner(System.in); 
    
    int ticketAmnt;
    
    do
    {
        System.out.println("How many tickets will you be generating?");
        ticketAmnt = entry.nextInt();
    }
    while(ticketAmnt<1 || ticketAmnt>100);
    
    int randomNumbers[] = new int[6];
    
    for (int i = 0; i <randomNumbers.length; i++)
    {
        randomNumbers[i] = (int) (Math.random() * 50);
    }
    
    int lottery [][] = new int [ticketAmnt][randomNumbers.length];
    
    for (int i = 0;i<ticketAmnt;i++)
    {
        for(int j = 0;j<randomNumbers.length;j++)
        {
            if (lottery[j] == randomNumbers) // Here, code checks if same random number generated before.
            {
                int randomNum = (int) (Math.random() * 50); // If random number is same, another number generated.
            }
        }
    }
    for (int i = 0; i < lottery.length; i++)
        System.out.print(lottery[i] + " ");

Your random number generator for generating the lottery numbers on each ticket is wrong. Your current generator will push out 0 which is not desired in this case. You require numbers inclusively from 1 to 49 . If you want to use the Math.random() method then you should perhaps do it this way:

int randomNumber = (int)(Math.random() * 49 + 1);

Don't fall into that trap where you think that adding the 1 to 49 and using 50 to save a math step is going to help you. Math doesn't work that way. Always remember, in an equation, multiplication is always carried out before addition or subtraction.

As already mentioned in comments the string your are seeing ( similar to: I@38af3868 ) is the array object's hashcode which at a glance is pretty much meaningless but there is information there and this hashcode is used for other purposes. The link in comments provided by @tgdavies which is written by @Duncan Jones covers this quite nicely. If you want to display the contents of your let's say randomNumbers[] array to the console window then you can use the java.util.Arrays.toString() method, for example:

System.out.println(java.util.Arrays.toString(randomNumbers);

or you can iterate through the array with something like a for loop and display (or access) the array contents that way, for example:

for (int i = 0; i < randomNumbers.length; i++) {
    System.out.println("Array Element at index " + i + " is: --> " + randomNumbers[i]);
}

It would be a little different for your other array, the two dimensional (2D) int array with the variable name of lottery (lottery[][]). A Multi Dimensional Array in Java (like a 2D Array) is an Array of Arrays so you need to sort of treat it as such. Think of a 2D Array as if it were a Table with rows and columns. The outer Array holds the Rows and the inner Array hold the columns for each row. To access the inner arrays (columns) you need to first access the outer (rows) arrays, for example:

for (int row = 0; row < lottery.length; row++) {
    for (int column = 0; column < lottery[row].length; column++) {
        System.out.println("Element in Row index: " + rows + " Column index: " 
                         + column + " is: --> " + lottery[row][column]);
    }
    System.out.println();
}

Consequently for a quick display you can also use the java.util.Arrays.deepToString() method, for example:

System.out.println(java.util.Arrays.deepToString(lottery));

When generating your random numbers for each ticket the are a couple things you obviously need to check for:

  1. When generating a set of 6 numbers make sure no set contains duplicate numbers. Each number in a set of 6 must be unique within that set.
  2. When a set of 6 numbers has successfully been generated with unique numbers make sure that set with the very same numbers has not already been issued as a ticket. Although the odds of this is very slim... it is possible .

For the first item, you'll want to do this as the numbers are being generated. A while loop can take care of this business and only allow the code to continue on if in fact all values within the Array are unique, for example:

int haveSix = 0; // Used as an index counter
// If we don't have 6 unique numbers then keep looping until we do.
while (haveSix < 6) {
    // Pull a random number from 1 to 49 inclusive.
    int randomNum = (int) (Math.random() * 49 + 1);   
    unique = true; // Assume the generated number is unique
    // Check the generated number to see if it's already in the array.
    for (int n : randomNumbers) {
        if (n == randomNum) {
            /* Yup..it's already in the array so unique 
               goes false and we break out of this loop. */
            unique = false;
            break;
        }
    }
    /* If the generated number is unique to what is already 
       in the set then add it to the array.           */
    if (unique) {
        // Add the generated number to the Array.
        randomNumbers[haveSix] = randomNum;
        haveSix++; // Increment the index counter
    }
    /* If it's not unique (the unique flag is false) then we loop 
       again and pull for another random number. We'll keep looping 
       like this until haveSix = 6 to satisfy the 'while' loop condition. 
       The haveSix variable will only increment if the random number 
       is unique to the current array.  */
}

At this point you would want to Sort your randomNumbers[] array in ascending order. This serves two purposes, first, it helps when checking ticket sets already contained within the lottery[][] 2D Array against the current set held in the randomNumbers[] array for uniqueness. After all, you don't want to issue two of the same set of numbers. Secondly, it looks nicer when you print out the tickets:)

To sort your randomNumbers[] array in ascending order you can use the java.util.Arrays#sort() method, for example:

java.util.Arrays.sort(randomNumbers);

That's it...sorted. Now all that is required is to ensure that the set of ticket numbers contained within the randomNumbers[] Array is not already in the lottery[][] 2D Array. To do this you will need to iterate through the lottery[][] array and compare the arrays already stored there (if any) with the randomNumbers[] array, for example:

unique = true;
for (int[] ary : lottery) {
    // Is the set UNIQUE?
    if (Arrays.toString(ary).equals(Arrays.toString(randomNumbers))) {
        // Nope... break out and create another new set of ticket numbers
        unique = false;
        break;
    }
}

Notice how the Arrays.toString() method is used to convert all arrays to string so that they can be compared to each other for equality. Now you can see why sorting is important here. If the boolean unique variable (flag) falls to false then the lottery[][] 2D array already contains the same set held in the randomNumbers[] array which is no good. We can't add that set to lottery[][] . We'll need to generate another set of numbers which of course then means, that ticket is not fulfilled and we need to loop again to generate a new set. If it is found the set is unique then it can be added to the lottery[][] 2D Array.

All together, the whole thing would look something like this:

import java.util.Arrays;
import java.util.Scanner;


public class Lotto649 {

    
    public static void main(String[] args) {
        Scanner entry = new Scanner(System.in);

        int ticketAmnt;
        
        do {
            System.out.print("How many tickets will you be generating (1 to 100)? --> ");
            ticketAmnt = entry.nextInt();
        } while (ticketAmnt < 1 || ticketAmnt > 100);

        int[] randomNumbers;
        int lottery[][] = new int[ticketAmnt][];

        int ticketCount = 0;
        boolean unique = false;
        while (ticketCount < ticketAmnt) {
            randomNumbers = new int[6];
            int haveSix = 0;
            while (haveSix < 6) {
                int randomNum = (int) (Math.random() * 49 + 1);
                unique = true;
                for (int n : randomNumbers) {
                    if (n == randomNum) {
                        unique = false;
                        break;
                    }
                }
                if (unique) {
                    randomNumbers[haveSix] = randomNum;
                    haveSix++;
                }
            }
            /* Sort the numbers within the Array in Ascending order.
               This helps to check sets of ticket numbers later and,
               it looks better when the tickets are printed out. :) */
            Arrays.sort(randomNumbers);

            /* Array is now ready to add to the lottery[][] array but first
               let's make sure the set is uniqie to all other sets already
               within the lottery[][] array.                         */
            unique = true;
            for (int[] ary : lottery) {
                // Is the set UNIQUE?
                if (Arrays.toString(ary).equals(Arrays.toString(randomNumbers))) {
                    // Nope... break out and create another new set of ticket numbers
                    unique = false;
                    break;
                }
            }
            if (unique) {
                lottery[ticketCount] = randomNumbers;
                ticketCount++; 
            }
        }
        
        // Print the lottery tickets to Console Window:
        for (int i = 0; i < lottery.length; i++) {
            System.out.println("Ticket #" + (i + 1) + ": --> " 
                    + Arrays.toString(lottery[i]).replaceAll("[\\[\\]]", ""));
        }
    }
}

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