Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomizing in Java

Tags:

java

random

I have 4 Strings to represent people and 4 Strings to represent names.

I'm trying to randomize them so that every time I start my application, my four people will have different names, but no one can have the same name during runtime.

Example:

String person_one;
String person_two;
String person_three;
String person_four;

String name_one = "Bob";
String name_two = "Jane";
String name_three = "Tim";
String name_four = "Sara";

Hope this makes some sense.

like image 898
EGHDK Avatar asked Dec 21 '22 14:12

EGHDK


2 Answers

You can use Collections.shuffle():

List<String> names = new ArrayList<String>();
names.add("Bob");
names.add("Jane");
names.add("Tim");
names.add("Sara");

Collections.shuffle(names);

person_one = names.get(0);
person_two = names.get(1);
person_three = names.get(2);
person_four = names.get(3);
like image 137
Joey Avatar answered Dec 31 '22 10:12

Joey


You can use Collections.shuffle().

like image 27
Greg Kramida Avatar answered Dec 31 '22 08:12

Greg Kramida