user2459711
user2459711

Reputation: 1

create a random for strings

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

Answers (3)

PATRY Guillaume
PATRY Guillaume

Reputation: 4337

You could also use the RandomStringUtil class of apache commons.lang

Upvotes: 1

PSR
PSR

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

Thilo
Thilo

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

Related Questions