DESKTOP-GVU7VL7_20200905-陈小丽
遇到的问题
编写程序实现彩票(大乐透)号码生成器。由于没有买过彩票,考试的时候连题都读不懂。
下午老师讲了一下,原理明白了,代码实现还得多想想、多看看。
public class DaLeTou1 {
private Random rand = new Random();
private StringBuffer buffer = new StringBuffer();
/**
* 随机产生不重复的length个正整数
* @param bound 随机产生的正整数的最大值
* @param length 需要随机产生的正整数的个数
* @return
*/
public int[] produce ( int bound , int length ) {
if( bound <= 0 ) {
throw new IllegalArgumentException( "随机数的最大值不能小于零" );
}
if( length <= 0 ) {
throw new IllegalArgumentException( "随机数的个数不能小于零" );
}
//创建一个新的数组对象
int[] array = new int[ length ];
for( int i = 0 ; i < length ; i++ ) {
int temp = rand.nextInt( bound ) + 1 ;
boolean notExists = true ; // 假设新生成的随机数在数组中是不存在的
for( int j = 0 ; j < i ; j++ ) {
if( temp == array[ j ] ) {
notExists = false ; // 推翻假设
i-- ;
break;
}
}
if( notExists ) {
array[ i ] = temp ;
}
}
return array ;
}
/**
* 将数组转换为我们需要的字符串形式
* @param array
* @return
*/
public String toString( int[] array ) {
buffer.setLength( 0 );
for (int i = 0; i < array.length; i++) {
int element = array[ i ] ;
buffer.append( element < 10 ? "0" + element : element );
buffer.append( " " );
}
return buffer.toString();
}
public static void main(String[] args) {
DaLeTou1 d = new DaLeTou1();
int[] x = d.produce( 34 , 5 );
int[] y = d.produce( 12 , 2 );
System.out.println( d.toString( x ) + d.toString( y ) );
}
}
吐槽
左眼皮今天跳了一天,跳的心里好难受啊,干啥都静不下心来。
近期评论