-4

I have a list of 4 names that I want to divide into 2 groups of 2 each.

//the variables are defined by user input

String name1=null, name2=null, name3=null, name4=null;

//Now i need something to choose 2 random names and print them out 

System.out.println("Team A = name 1, name 2");
System.out.println("Team B = name 3, name 4");

etc.

It needs to be completely random. For when I add more names. It should take different group each time, and a name can only be used once.

I have tried with this:

List<String> list = new ArrayList<>(); 

 list.add(name1); 
 list.add(name2); 
 list.add(name3); 
 list.add(name4); 

 selecto obj = new selecto(); 

 System.out.println(obj.getRandomElement(list)); 
 } 

 public int getRandomElement(List<Integer> list) 
 { 
    Random rand = new Random(); 
    return list.get(rand.nextInt(list.size())); 

This works perfectly with the integer but not strings.

Envy
  • 1
  • 3
  • Possible duplicate of [Java: how can I split an ArrayList in multiple small ArrayLists?](https://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists) – Gatusko Sep 10 '19 at 12:34
  • 3
    Please first give it a try yourself first and if you have not succeeded, post your **valid Java code** in the question – Udith Gunaratna Sep 10 '19 at 12:34
  • 1
    I have no idea what this question is about. First you create 4 empty variables and then "divide them" into 2 groups of 2, even tho you've said you want groups of 4. – Amongalen Sep 10 '19 at 12:40

1 Answers1

0

Create a list with random strings, you'll have to add them yourself if you want them to make sense.

 List<String> names = new ArrayList<>() {{ add("Name1"); add("Name2"); add("Name3"); }};

Now populate your list by choosing a random element from the list above and removing it so you won't get duplicates, like this:

list.add(names.remove(rand.nextInt(names.size())));

If you also need the names to be generated randomly, check this question: How to generate a random alpha-numeric string?

emankcin
  • 76
  • 3