首页 > 解决方案 > 创建一个允许用户选择玩家数量的java彩票程序

问题描述

我正在创建一个使用集合来存储数字的彩票程序。用户输入他们的数字,并将其存储在一个集合中,然后计算机生成一些随机数,并将其存储在另一个集合中。然后比较这 2 个集合,并取出相交。

用户可以选择运行彩票程序的周数,即计算机每周生成新值并对照用户编号检查它们。

我应该让代码为不同数量的玩家运行,即用户应该能够选择每周有多少玩家,并且代码应该打印出每个玩家每周得到的东西。

    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();
    }

我可以创建固定数量的玩家来玩,但我不知道如何让用户选择他们想要的玩家数量

标签: javaset

解决方案


创建一个“玩家”列表

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);
}

推荐阅读