I am very new to Java, so this could seem too easy for most people....Is this completely wrong?
My question is how to write a method selectRandom(String[] names),
which returns a randomly selected name from the given array.
Each name should be selected with equal probability.
public static String selectRandom(String[] names)
{
String num = names[0];
int[]newArray = new int[names.length];
for(int i =0; i<names.length;i++)
{
Random r = new Random();
int ranNum= r.nextInt(names.length)+1;
num = names[ranNum];
}
return num;
}
You can simply generate a random number up to the array size, and get the value at that index.
public static String selectRandom(String[] names) {
if (name != null && names.length > 0) {
Random r = new Random();
return names[r.nextInt(names.length)];
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With