user11395435
user11395435

Reputation: 11

Java lottery program, having trouble comparing outputs

I have to do an 'instant lottery' program in my first computer science class. All semester my professor has read verbatim from the book, so now I am a little lost, truthfully. I know how to do most of it, but am just having trouble figuring out array sort and how to compare user input and the random number output. My professor refuses to answer questions about take home assignments and has banned the use of anything except: arrays, loops and math.random- so no sets or anything more complex that could help. I've seen other programs that compile, but all with sets.

I have the code for user input of the lottery numbers and to generate the output of the random numbers. I can most likely also figure out how to print the payout with if/else. I just need to know how to get the program to compare the numbers an figure out if the user is a "winner" or not.

import java.util.Scanner;

public class TheLottery {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in); //user input of their lottery numbers

        System.out.print("Enter number 1: ");
        int num1 = keyboard.nextInt();
        System.out.print("Enter number 2: ");
        int num2 = keyboard.nextInt();
        System.out.print("Enter number 3: ");
        int num3 = keyboard.nextInt();
        System.out.print("Enter number 4: ");
        int num4 = keyboard.nextInt();
        System.out.print("Enter number 5: ");
        int num5 = keyboard.nextInt();
        System.out.print("Enter number 6: ");
        int num6 = keyboard.nextInt();
    }


    int[] lottery = new int[6];
    int randomNum;
    {

    for (int i = 0; i < 6; i++) {
        randomNum = (int) (Math.random() * 50); // Random number created here.
        for (int x = 0; x < i; x++) {
            if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
            {
                randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
                x = -1; // restart the loop
            }

        }
        lottery[i] = randomNum;
    }

    for (int i = 0; i < lottery.length; i++)
        System.out.print(lottery[i] + " "); //print random numbers
    }
}

the final program should have the user enter 6 numbers, the program compare the numbers for matches, figure out if the user is a 'winner', show the prize and an added thing is show how much they spent (each 'ticket' is $1) vs how much they won. So far all that outputs is the scanner and random numbers

Upvotes: 1

Views: 1247

Answers (2)

KevinO
KevinO

Reputation: 4403

The specific question has to do with how to do the comparison and figuring a "winner". It isn't clear what makes the definition of "winner".

Based upon my comment, and as shown in the answer by @szoore, I would use an array to collect the input. I'd use a method to collect (since one can change to use a different method for the selections, which makes testing easier).

/**
 * Obtain the specified number of entries from the user
 */
public static int[] getUserSelections(final int numSelections)
{
    Scanner in = new Scanner(System.in);

    // read N entries from the user
    int[] nums = new int[numSelections];

    // NOTE: no error processing in this loop; should be refined
    //   bad numbers (e.g., negative, too large), duplicate entries, etc.
    //     need to be removed
    for (int i = 0; i < numSelections; ++i) {
        System.out.print("Enter number " + (i + 1) + ": ");
        nums[i] = in.nextInt();
    }

    return nums;
}

The OP has a basic generation for the lottery numbers, but again I'd use a method. This has a slight refinement to the duplicate check, by using a method, and also allows the same duplicate check method to be later used for checking matches:

public static int[] getLotteryNumbers(final int numSelections)
{
    // the largest number to be selected; all numbers between
    //   1 and maxNum (inclusive) will have equal(-ish) probability
    //   of being generated
    final int maxNum = 50;

    int[] lottery = new int[numSelections];

    Random rnd = new Random();


    // make N random selections, and ensure we don't have duplicates
    for (int i = 0; i < numSelections; ++i) {
        boolean generate = true;
        while (generate) {
            int sel = rnd.nextInt(maxNum) + 1;
            generate = numberInArray(sel, lottery);
            if (! generate) {
                lottery[i] = sel;
            }
        }
    }

    return lottery;
}


/**
 * Returns true if the specific queryNum is found in the pastSelections
 *  Could be slightly optimized by passing how many selections have
 *  already been made
 */
public static boolean numberInArray(int queryNum, int[] pastSelections)
{
    // look at each element and see if already there; exit via return
    //  if so
    for (int i = 0; i < pastSelections.length; ++i) {
        if (pastSelections[i] == queryNum) {
            return true;
        }
    }

    return false;
}

The use of the method 'numberInArray' then allows for fairly easy check on how many numbers match:

    // see how many match
    int matches = 0;

    // see if the user entry exists in the lottery; if so, we
    //  have a match
    for (int i = 0; i < userEntries.length; ++i) {
        if (numberInArray(userEntries[i], lottery)) {
            ++matches;
        }
    }


    System.out.printf("Found %2d matches%n", matches);

Determining payouts, etc. is straight forwarding using if/else or (perhaps better) a switch based on the number of matches.

Also, the entries and lottery selections should probably be sorted. It isn't clear if the built-in sort may be used or not. Write the sort method as appropriate:

/**
 * Sorts the array; implement sorting as needed
 */
public static void sort(int[] arr)
{
    Arrays.sort(arr);
}

/*
 * outputs the array if one cannot use Arrays.toString(arr)
 */
public static void outputArray(int[] arr)
{
    for (int i = 0; i < arr.length; ++i) {
        System.out.printf("%2d ", arr[i]);
    }

    System.out.println();
}

Sample main:

public static void main(String[] args)
{
    // how many options for the lottery; here it is 6
    final int numEntries = 6;

    // this method obtains from user
    int[] userEntries;

    userEntries = getUserSelections(numEntries);

    sort(userEntries);

    // display User selections
    outputArray(userEntries);


    int[] lottery = getLotteryNumbers(numEntries);

    sort(lottery);

    // display lottery numbers
    outputArray(lottery);

    // see how many match
    int matches = 0;

    // see if the user entry exists in the lottery; if so, we
    //  have a match
    for (int i = 0; i < userEntries.length; ++i) {
        if (numberInArray(userEntries[i], lottery)) {
            ++matches;
        }
    }


    System.out.printf("Found %2d matches%n", matches);

    //
    // TODO: calculate winnings based upon the number of matches
    //
}

Upvotes: 0

szoore
szoore

Reputation: 11

It looks like you obtained six numbers then didn't use them. Your lottery array is automatically initialized to zero. I think you're trying to compare an array with inputs to a random array, so you need a loop to put your entered values into. After you do that, initialize your random array, then just compare the arrays.

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

            int[] lottery = new int[6];

            System.out.println("Enter " + lottery.length + " numbers: ");
            for (int i = 0; i < lottery.length; i++) {
               lottery[i] = in.nextInt();
         }

Upvotes: 1

Related Questions