我正在努力建立一支由我所拥有的特定成员组成的团队。这是我到目前为止所做的。
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
/* Putting all team-mates in HashMap */
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.put("d", 4);
/* Printing out the random name and the Unique number with it*/
List<Integer> valuesList = new ArrayList<Integer>(map.values());
List<String> keyList = new ArrayList<String>(map.keySet());
System.out.println("The Team members are :");
for (int i = 0; i < 3; i++)
{
int randomIndex = new Random().nextInt(valuesList.size());
Integer randomValue = valuesList.get(randomIndex);
String randomKey = keyList.get(randomIndex);
System.out.println(randomValue+" "+randomKey);
}
}
}
当我运行它时,我在列表中得到重复,我是否使用Collections.shuffle(valuesList)?
谢谢。
答案 0 :(得分:1)
您可以随机两次获得相同的数字,因此Collections.shuffle(...)
应该这样做。
答案 1 :(得分:0)
如果a,b,c,d就是你所追求的,我就是这样做的:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
/* Putting all team-mates in a List*/
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
/* Printing out the random name */
System.out.println("The Team members are :");
for(int i = 0; i < 3; i++)
{
int randomIndex = new Random().nextInt(list.size());
//Integer randomValue = valuesList.get(randomIndex);
String randomValue = list.remove(randomIndex);
//String randomKey = keyList.get(randomIndex);
System.out.println(randomValue);
}
}
}
选择后从列表中删除所选元素将确保它们不再出现。
也减少了行数。