Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return random string Arrray Java

Tags:

java

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;  
}
like image 657
user1721548 Avatar asked Nov 19 '25 06:11

user1721548


1 Answers

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;
}
like image 133
FThompson Avatar answered Nov 20 '25 20:11

FThompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!