Question:
Picking a random string from an array in Java?
SP
2012-02-14 13:46:17 UTC
I am trying to figure out how to pick out a string from an array of strings and I asked my friend and he said that i could use this code (Yahoo doesn't let me include the tabs/spaces at the beginning of the lines, so it looks kind of weird):

public class RandomGenerator {
public static void main(String[] args) {
String[] array = {"asd","asdf","asdfg","asdfgh","asdfghj"};
String results = array[Math.random()*(array.length-1)];

}
}

Can I have three arrays, each of which has a random string picked out of it? What parts do I have to change to make it so the Math.random functions do not interfere with each other? Would this be the way to do that?

public class RandomGenerator {
public static void main(String[] args) {
String[] array = {"asd","asdf","asdfg","asdfgh","asdfghj"};
String results = array[Math.random()*(array.length-1)];
String[] array1 = {"asd","asdf","asdfg","asdfgh","asdfghj"};
String results = array1[Math.random()*(array1.length-1)];
String[] array2 = {"asd","asdf","asdfg","asdfgh","asdfghj"};
String results = array2[Math.random()*(array2.length-1)];

}
}

Also, can I make them all display at once in a text box in order with the click of a button? I'm pretty new to this, so thank you for your help.
Three answers:
McFate
2012-02-14 14:03:25 UTC
For what it's worth:



String myStrings[] = // whatever

String randomStr = myStrings[ (int) (Math.random() * myStrings.length) ];



That's the proper way. Math.random() always returns a value strictly less than 1, so when multiplied by myStrings.length and truncated to an int, it will be a random value from 0 to length-1. The "-1" that you have in your equations means that you will never randomly pick the last element of the array. Also I'm not sure you can use a double value as an array index without the compiler complaining. I'd cast it to int first.



Yes, the code you have written should pick three independent random Strings, one from each array. But I don't think it will compile because you reuse the same variable name (results) three times. Perhaps you want to call them results, results1, and results2, or something like that?



@M
green meklar
2012-02-14 21:16:26 UTC
Absolutely. You don't have to change anything; the Math.random() method cannot 'interfere'.



Here is a method that does this for any particular array of String:



public static String randomString(String[] sa)

{

return sa[(new Random()).nextInt()%sa.length];

}



I haven't tested this code, but it's loosely based on another method that I use fairly frequently, so it should work.
anonymous
2012-02-15 19:03:10 UTC
yes


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...