闲来无事,我做了一个彩票号码生成器,该程序是个通用程序,方法generateNumber(M, N, P)表示M选N的彩票买了P注,
例如:generateNumber(35, 7, 5);表示35选7买5注.本程序在JDK1.5,Eclipse3.1.2下测试成功!
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
/** */ /**
* @author 我为J狂
*
*/
public class GenerateNumber
{
public static void generateNumber( int m, int n, int p)
{
for ( int i = 0 ; i < p; i ++ )
{
Set < Integer > numbers = new HashSet < Integer > ();
while ( true )
{
Random random = new Random();
int newNumber = random.nextInt(m);
numbers.add(newNumber + 1 );
if (numbers.size() == n)
break ;
}
List < Integer > sortNumbers = new ArrayList < Integer > (numbers);
String numberStr = "" ;
Collections.sort(sortNumbers);
for ( int num : sortNumbers)
{
String number = "" ;
if (num < 10 )
number = " 0 " + num;
else
number = String.valueOf(num);
if ( ! numberStr.equals( "" ))
numberStr += " , " ;
numberStr += number;
}
System.out.print(numberStr);
System.out.println();
}
}
public static void main(String[] args)
{
generateNumber( 35 , 7 , 5 ); // 35选7买5注
}
}