5

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.

5
  • Look up modulo, and the random generation in java Commented Oct 17, 2012 at 14:59
  • 1
    What have you tried? Have you ever done anything similar, in another language or with different data that you think could be useful here? Commented Oct 17, 2012 at 15:00
  • Put them in an array and shuffle it. Commented Oct 17, 2012 at 15:00
  • You could look at my earlier answer which is similar to this problem. stackoverflow.com/a/12795958/713414 Commented Oct 17, 2012 at 15:00
  • It makes sense.. it's just a little trickier than first-glance suggests. Commented Oct 17, 2012 at 15:01

2 Answers 2

9

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); 
Sign up to request clarification or add additional context in comments.

6 Comments

This is awesome. Had no idea java had something like this. Perfect. Thanks guys.
@Joey You might want to use names.get(i) instead of names[i] and Collections.shuffle(names) instead of names.shuffle() ;)
Baz: Argh, that's what I get for a Java detour while doing C# :-)
@EGHDK Java has one of the most complete and best thought out APIs there is.
user1598390, that may well be subject to debate. A lot of places in Java's APIs are horrible.
|
2

You can use Collections.shuffle().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.