Reputation: 1
I recently started java programming and I was wondering I wrote some string and initialized their variables but how can I now randomize those variables so that one is chosen randomly everytime. I'm sorry if this is vague and please be expalantory I'm only a beginner
Regards
Upvotes: 0
Views: 129
Reputation: 4337
You could also use the RandomStringUtil class of apache commons.lang
Upvotes: 1
Reputation: 40338
try this
String str= "your string";
int n = str.length();
Random random= new Random();
String randomString= "";
for (int i = 0; i <length you want; i++)
randomString+= new String(str.charAt(random.nextInt(n)));
Upvotes: 3
Reputation: 262794
If you want to choose one object at random from a number of choices, put them in an array, and then pick a random index.
Object[] choices = new Object[] { a, b, c};
int randomIndex = Math.random() * choices.length;
Object picked = choices[randomIndex];
Upvotes: 2