java产生不重复的随机数

import java.io.*;


public class test
{
 public static void main (String [] str)
 {
   final int num = 20;
  
  int Random[] = new int[num];
  for(int i = 0 ; i < num ; i++)
  {
  // int ran=-1;
   while(true)
   {
    int ran = (int)(num*Math.random());
    for(int j = 0 ; j < i ; j++)
    {
     if(Random[j] == ran) 
     {
      ran = -1;
      break;
     } 
    }
    if(ran != -1) 
    {
     Random[i] = ran;
     break;
    }
    
   }
   
  }
  for(int i = 0 ; i < num ; i ++)
  {
   System.out.print(Random[i]+",");
  }
 }
}

 

posted @ 2016-11-29 10:36  客舍青  阅读(17250)  评论(0编辑  收藏  举报