0
String a="aaa";
String b="bbb";
String c="ccc";
String d="ddd";

String p,q,r,s;

How can I assign values to p,q,r,s randomly from a,b,c,d?

Like p should have value from a,b,c,d and similarly for q,r,s

But the value should not repeat.

Mat
  • 202,337
  • 40
  • 393
  • 406
ashish.n
  • 1,234
  • 14
  • 30
  • 2
    Welcome to SO. See @BalusC's answer from here: http://stackoverflow.com/questions/4702036/take-n-random-elements-from-a-liste. Also, it helps to do a search (here or on Google), before posting new questions. – Perception Feb 11 '12 at 12:47

3 Answers3

3

The easiest way to do it is probably to just put all the strings in a array (or list, or similar), shuffle the list and assign the first value in the shuffled array to p, the second to q, etc.

Here's an example of how to do this:

String[] strings = new String[] {
    "aaa", "bbb", "ccc", "ddd"
};

Collections.shuffle(Arrays.asList(strings));

String p = strings[0],
       q = strings[1],
       r = strings[2],
       s = strings[3];
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
2

Create an array of a,b,c,d, and use a random 0~3 index to get the value.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Add your Strings to a List<String> and then use java.util.Random class's nextInt(sizeOfList) method.

Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73