从字符串数组中随机选择

时间:2018-10-11 21:07:41

标签: java arrays

我遇到了一个小问题。我有一个家庭作业,需要从字符串数组中“随机”选择一个字符串。练习的目的是编写一个选择随机(插入)名称的代码。我的代码:

 public void run() {
        int userSelection = -1;
        int userAmount = 0;
        String[] users = new String[userAmount];
        int[] amountChosen = new int[userAmount];

        while (userSelection != 0) {
            drawMenu();
            System.out.println();

            //user selecting the menu choice
            System.out.print("Make a selection from the menu: ");
            userSelection = userInput();
            System.out.println();

            //forcing the user to give one of the allowed values
            while (userSelection < 0 || userSelection > 4) {
                System.out.print("That is invalid input. try again: ");
                userSelection = userInput();
            }

            //adding users
            if (userSelection == 1) {
                System.out.print("How many users do we have?");
                userAmount = userInput();
                users = new String[userAmount];
                amountChosen = new int[userAmount];
                addUsers(users, userAmount); //returns user array with names
                System.out.println();
            }

            //selecting random user
             else if (userSelection == 2) {
                int playerSelect = (int) (Math.random()*userAmount);
                amountChosen[playerSelect]++;
                System.out.println(users[playerSelect] + " was chosen!");
                System.out.println();
            }

            //display the amount the users were chosen
            else{
                System.out.println("******** Turns ********");
                for (int i = 0; i < userAmount; i++){
                    System.out.println("* " + "[" + amountChosen[i] + "] " + users[i]);
                }
                System.out.println("***********************");
                System.out.println();
            }
        }
    }

如您所见,我现在有一个完全随机的用户选择。为了密切关注玩家的选择频率,我已经制作了“ int [] amountChosen”数组。目标是“选择一个随机播放器,也使其选择被选择次数最少的播放器”,因此从根本上讲,它需要选择选择量最少的字符串。 (另外:我知道我的代码在某些地方可能有点混乱和奇怪。我刚刚开始学习Java) 感谢您的回应!

2 个答案:

答案 0 :(得分:4)

我不会给出您任务的答案。但是,这是您要实现的目标的幼稚实现:

private void someMethod() {
    String[] strArray = {"foo", "bar", "foobar"};
    Random random = new Random();
    System.out.println(strArray[random.nextInt(strArray.length)]);
}

说明:

您可以使用0Random和字符串数组的长度之间取一个随机数,然后将其用作查询字符串数组的索引。

答案 1 :(得分:0)

如果我理解正确,您想随机选择所有玩家中选择最少的玩家之一吗?

  • 使用Map<String, Integer>和金额;
  • 使用最低金额的所有玩家过滤地图;
  • 使用Random.nextInt(amountOfLowest)

您可以使用Java Streams。

提示:•使用map.entrySet().stream()来流过地图元素•使用values()unboxed()min()获得最小值•使用filter()map()collect()收集所有金额最低的玩家的列表•使用List.get(new Random().nextInt(...))选择一个玩家。