How to randomly pick an element from an array

前端 未结 12 871
逝去的感伤
逝去的感伤 2020-11-22 16:48

I am looking for solution to pick number randomly from an integer array.

For example I have an array new int[]{1,2,3}, how can I pick a number randomly?

12条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 17:13

    package workouts;
    
    import java.util.Random;
    
    /**
     *
     * @author Muthu
     */
    public class RandomGenerator {
        public static void main(String[] args) {
         for(int i=0;i<5;i++){
             rndFunc();
         } 
        }
         public static void rndFunc(){
               int[]a= new int[]{1,2,3};
               Random rnd= new Random();
               System.out.println(a[rnd.nextInt(a.length)]);
           }
    }
    

提交回复
热议问题