Skip to content

creating a java lottery program that allows the user to select the number of players

I am creating a lottery program that uses a set to store the numbers. The user inputs their number, and it’s stored in a set, then the computer generates some random number, and this is stored in a different set also. The 2 sets are then compared, and the intersect is taken out.

The user can select the number of weeks to run the lottery program i.e. each week the computer generates new values and checks them against the user number.

I’m supposed to make the code run for a varying amount of players i.e the user should be able to select how many players for each week and the code should print out what each player got per week.

    public void run(int week) {
        int counter=0;
        HashSet<Integer> use1=new HashSet(); stores the input into a set
        HashSet<Integer> use2=new HashSet();
        HashSet<Integer> use3=new HashSet();
    
    
        use1=userLottery(use1); // runs the method that gets the users input
        use2=userLottery(use2);
        use3=userLottery(use3);
    
        System.out.println("");
        do {
            week--;
            counter++;
             HashSet <Integer>comp=new HashSet();
             comp=computerLottery(comp);    //computer generated numbers
     
             System.out.println("week : "+counter);
             checkLottery(comp,use1);
             checkLottery(comp,use2);
             checkLottery(comp,use3);
             System.out.println("");
             comp.clear();
     
         } while(week>0);
         use.clear();
    }

I’m able to create a fixed amount of players to play but I can’t figure out how to allow the user to select the number of players they want

Answer

Create a List of “players”.

public void run(int week) {
    int numberOfPlayers = // obtained from user
    List<HashSet<Integer>> players = new ArrayList<>(numberOfPlayers);
    for (int i = 0; i < numberOfPlayers; i++) {
        players.add(new HashSet<>());
    }
    for (HashSet<Integer> player : players) {
        player = userLottery(player);
    }
    int counter = 0;
    do {
        week--;
        counter++;
        HashSet<Integer> comp = new HashSet<>();
        comp = computerLottery(comp); // computer generated numbers

        System.out.println("week : " + counter);
        for (HashSet<Integer> player : players) {
            checkLottery(comp, player);
        }
        System.out.println("");
        comp.clear();
    } while (week > 0);
}