Reputation: 297
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;
}
Upvotes: 2
Views: 3836
Reputation: 28687
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;
}
Upvotes: 5
Reputation: 380
Randomly choose an index and return the corresponding String
in names
. There is a Random class to do get random numbers in java. Also check nextInt method.
public static String selectRandom(String[] names)
{
Random rand = new Random();
int index = rand.nextInt(names.length);
return names[index];
}
Upvotes: 0
Reputation: 1385
public static String selectRandom(String[] names)
{
Random r = new Random();
int ranNum= r.nextInt(names.length);
return names[ranNum];
}
You don't need most of the codes inside your method. Maybe you should try something like this?
Upvotes: 4